简体   繁体   English

滚动图像时,Android Studio RecyclerView严重滞后

[英]Android Studio RecyclerView strongly lagging while scrolling images

I have a RecyclerView filled by posts from different users. 我有一个RecyclerView,里面充斥着来自不同用户的帖子。 Each post has a description, the name of the user, the time and an image (I use Picasso). 每个帖子都有说明,用户名,时间和图像(我使用毕加索)。 Unfortunately when I start scrolling the view a very strong lag makes impossible to use the app. 不幸的是,当我开始滚动视图时,非常滞后使得无法使用该应用程序。

I read many posts on the site but the only thing that helps me has been adding recyclerView.setItemViewCacheSize(20). 我在该网站上阅读了许多帖子,但唯一对我有所帮助的事情是添加了recyclerView.setItemViewCacheSize(20)。 However, the lag is still noticable. 但是,滞后仍然很明显。 Here is my PostListActivity's code and layout (the activity where I put the recyclerview): 这是我的PostListActivity的代码和布局(我在其中放置recyclerview的活动):

public class PostListActivity extends AppCompatActivity {

private FirebaseDatabase mDB;
private DatabaseReference mDBRef;
private FirebaseUser mUser;
private FirebaseAuth mAuth;
private RecyclerView recyclerView;
private BlogRecyclerAdapter blogRecyclerAdapter;
private List<Blog> blogList;
private DrawerLayout mDrawerLayout;
ExpandableListAdapter mMenuAdapter;
ExpandableListView expandableList;
List<ExpandedMenuModel> listDataHeader;
HashMap<ExpandedMenuModel, List<String>> listDataChild;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post_list);

    final ActionBar ab = getSupportActionBar();





    BottomNavigationView bottomNavigationView = (BottomNavigationView)
            findViewById(R.id.bottom_navigation_view);

    bottomNavigationView.setOnNavigationItemSelectedListener(
            new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.action_PDFPOSTLIST:
                            if (mUser != null && mAuth != null){
                                startActivity(new Intent(PostListActivity.this, PDFPostListActivity.class));
                                finish();
                            }
                            break;

                    }
                    return false;
                }
            });





    /* to set the menu icon image*/
    ab.setHomeAsUpIndicator(android.R.drawable.ic_menu_sort_by_size);
    ab.setDisplayHomeAsUpEnabled(true);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    expandableList = (ExpandableListView) findViewById(R.id.navigationmenu);
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

    if (navigationView != null) {
        setupDrawerContent(navigationView);
    }

    prepareListData();
    mMenuAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild, expandableList);

    // setting list adapter
    expandableList.setAdapter(mMenuAdapter);

    expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long l) {
            //Log.d("DEBUG", "submenu item clicked");
            if (groupPosition == 3 && childPosition == 2) {
                startActivity(new Intent(PostListActivity.this, QuartaBUsersActivity.class));
            }
            return true;
        }
    });
    expandableList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
        @Override
        public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
            //Log.d("DEBUG", "heading clicked");
            return false;
        }
    });

    //Recupero dell'istanza di autenticazione di Firebase
    mAuth = FirebaseAuth.getInstance();
    mUser = mAuth.getCurrentUser();

    /*
     * Recuperiamo l'istanza del database,
     * il riferimento alla posizione figlia in cui vogliamo memorizzare dati e
     * manteniamo il database sincronizzato tra dispositivo e cloud
     */
    mDB = FirebaseDatabase.getInstance();
    mDBRef = mDB.getReference().child("Blog");
    mDBRef.keepSynced(true);

    //Istanziamo la lista di post
    blogList = new ArrayList<>();
    //Istanziamo ed effettuiamo il setup della RecyclerView
    recyclerView = (RecyclerView) findViewById(R.id.RecyclerView4Post);
    recyclerView.setHasFixedSize(true);
    recyclerView.setItemViewCacheSize(20);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    //Aggiungiamo un listener che monitori l'aggiunta di nuovi nodi figli nella posizione referenziata
    mDBRef.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            /*
             * Questo metodo viene invocato quando vengono aggiunti nuovi nodi figli.
             */
            //Preleviamo il post dal database
            Blog post = dataSnapshot.getValue(Blog.class);
            //Aggiungiamo il post alla lista
            //   if (post.getUserID().equals(mUser.getUid()))

            blogList.add(post);
            //Invertiamo l'ordine la lista per visualizzare i nuovi post per primi
            Collections.reverse(blogList);
            //Istanziamo l'adapter
            blogRecyclerAdapter = new BlogRecyclerAdapter(PostListActivity.this, blogList);
            //Settiamo l'adapter sulla RecyclerView
            recyclerView.setAdapter(blogRecyclerAdapter);
            //Notifichiamo all'adapter che il dataset è cambiato
            blogRecyclerAdapter.notifyDataSetChanged();
        }
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            /*
             * Questo metodo viene invocato quando vengono modificati dati sul nodo figlio.
             */
        }
        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
            /*
             * Questo metodo viene invocato quando viene rimosso un nodo figlio.
             */
        }
        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {
            /*
             * Questo metodo viene invocato quando cambia la priorità della posizione dei nodi figli.
             */
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            /*
             * Questo metodo viene invocato quando non è stato possibile reperire il dato.
             */
        }
    });


}


@Override
protected void onStart() {
    super.onStart();
}

private void prepareListData() {
    listDataHeader = new ArrayList<ExpandedMenuModel>();
    listDataChild = new HashMap<ExpandedMenuModel, List<String>>();

    ExpandedMenuModel item1 = new ExpandedMenuModel();
    item1.setIconName("Prime Liceo");
    item1.setIconImg(android.R.drawable.ic_menu_more);
    // Adding data header
    listDataHeader.add(item1);

    ExpandedMenuModel item2 = new ExpandedMenuModel();
    item2.setIconName("Seconde Liceo");
    item2.setIconImg(android.R.drawable.ic_menu_more);
    listDataHeader.add(item2);

    ExpandedMenuModel item3 = new ExpandedMenuModel();
    item3.setIconName("Terze Liceo");
    item3.setIconImg(android.R.drawable.ic_menu_more);
    // Adding data header
    listDataHeader.add(item3);

    ExpandedMenuModel item4 = new ExpandedMenuModel();
    item4.setIconName("Quarte Liceo");
    item4.setIconImg(android.R.drawable.ic_menu_more);
    // Adding data header
    listDataHeader.add(item4);

    ExpandedMenuModel item5 = new ExpandedMenuModel();
    item5.setIconName("PROF");
    item5.setIconImg(android.R.drawable.star_big_on);
    // Adding data header
    listDataHeader.add(item5);

    // Adding child data
    List<String> heading1 = new ArrayList<String>();
    heading1.add("1A                                   ");
    heading1.add("IA                                   ");
    heading1.add("1B                                   ");
    heading1.add("IB                                   ");

    List<String> heading2 = new ArrayList<String>();
    heading2.add("2A                                   ");
    heading2.add("IIA                                  ");
    heading2.add("2B                                   ");
    heading2.add("IIB                                  ");

    List<String> heading3 = new ArrayList<String>();
    heading3.add("3A                                    ");
    heading3.add("IIIA                                  ");
    heading3.add("3B                                    ");
    heading3.add("IIIB                                  ");

    List<String> heading4 = new ArrayList<String>();
    heading4.add("4A                                    ");
    heading4.add("IVA                                   ");
    heading4.add("4B                                    ");
    heading4.add("IVB                                   ");

    listDataChild.put(listDataHeader.get(0), heading1);// Header, Child data
    listDataChild.put(listDataHeader.get(1), heading2);
    listDataChild.put(listDataHeader.get(2), heading3);
    listDataChild.put(listDataHeader.get(3), heading4);

}


//Metodo chiamato dalla piattaforma per la creazione del menù
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    //Recupero dell'inflater e inflate del layout predisposto
    getMenuInflater().inflate(R.menu.main_menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            mDrawerLayout.openDrawer(GravityCompat.START);
            return true;

            case R.id.action_addPDF:
            /*
             * Quando l'utente sceglie l'item per aggiungere un nuovo post
             * lo direzioniamo verso l'activity appropriata
             */
            if (mUser != null && mAuth != null){
                startActivity(new Intent(PostListActivity.this, AddPDFActivity.class ));
            }
            break;

            case R.id.action_addPHOTO:
            /*
             * Quando l'utente sceglie l'item per aggiungere un nuovo post
             * lo direzioniamo verso l'activity appropriata
             */
            if (mUser != null && mAuth != null){
                startActivity(new Intent(PostListActivity.this, AddPostActivity.class ));
            }
            break;

            case R.id.action_signout:
            /*
             * Quando l'utente sceglie l'item per effettuare il logout
             * eseguiamo l'operazione e ritorniamo all'activity di login e registrazione
             */
            if (mAuth != null){
                mAuth.signOut();
                Toast.makeText(PostListActivity.this, "Utente disconnesso", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(PostListActivity.this, MainActivity.class));
                finish();
            }
            break;

            case R.id.action_myphoto:
                if (mUser != null && mAuth != null) {
                    startActivity(new Intent(PostListActivity.this, MyPostListActivity.class));
                }
                break;

            case R.id.action_mypdf:
                if (mUser != null && mAuth != null) {
                    startActivity(new Intent(PostListActivity.this, MyPDFPostListActivity.class));
                }
                break;

        case R.id.action_changeprofileimage:
            if (mUser != null && mAuth != null) {
                startActivity(new Intent(PostListActivity.this, ChangeProfileImageActivity.class));
            }
            break;




    }
    return super.onOptionsItemSelected(item);
}

private void setupDrawerContent(NavigationView navigationView) {
    //revision: this don't works, use setOnChildClickListener() and setOnGroupClickListener() above instead
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    menuItem.setChecked(true);
                    mDrawerLayout.closeDrawers();
                    return true;
                }
            });
}


@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}




}

And here is the layout: 这是布局:

<?xml version="1.0" encoding="utf-8"?>

<androidx.drawerlayout.widget.DrawerLayout android:id="@+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
xmlns:design="http://schemas.android.com/tools">




<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".PostListActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/RecyclerView4Post"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="?actionBarSize" />




</LinearLayout>


<include layout="@layout/bottom_navigation_layout" />

<com.google.android.material.navigation.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    >

    <ExpandableListView
        android:id="@+id/navigationmenu"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginTop="192dp"
        android:groupIndicator="@android:color/transparent"
        android:background="@android:color/white"
        >
    </ExpandableListView>

</com.google.android.material.navigation.NavigationView>

I also thought that the Adapter used for the recycler may be useful to understand the problem 我还认为用于回收站的适配器可能有助于理解问题

public class BlogRecyclerAdapter extends RecyclerView.Adapter<BlogRecyclerAdapter.ViewHolder> {
private Context context;
private List<Blog> blogList;
public BlogRecyclerAdapter(Context context, List<Blog> blogList) {
    this.context = context;
    this.blogList = blogList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.post_row, parent, false);
    return new ViewHolder(view, context);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    Blog blog = blogList.get(position);
    holder.nameUser.setText(blog.getNameUser());
    holder.surnameUser.setText(blog.getSurnameUser());
    holder.classUser.setText(blog.getClassUser());
    holder.description.setText(blog.getDescription());
    DateFormat dateFormat = DateFormat.getDateInstance();
    String formattedDate = dateFormat.format(new Date(Long.valueOf(blog.getTimeStamp())).getTime());
    holder.timeStamp.setText(formattedDate);
    final String imageURL = blog.getImage();
    Picasso.get().load(imageURL).into(holder.image);



}
@Override
public int getItemCount() {
    return blogList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
    private ImageView image;
    private TextView nameUser;
    private TextView surnameUser;
    private TextView classUser;
    private TextView description;
    private TextView timeStamp;
    private String userID;
    public ViewHolder(View itemView, Context ctx) {
        super(itemView);
        image = (ImageView) itemView.findViewById(R.id.postImageList);
        nameUser = (TextView)itemView.findViewById(R.id.textViewNAME);
        surnameUser = (TextView)itemView.findViewById(R.id.textViewSURNAME);
        classUser = (TextView)itemView.findViewById(R.id.textViewCLASS);
        description = (TextView) itemView.findViewById(R.id.postTextList);
        timeStamp = (TextView) itemView.findViewById(R.id.timeStampList);
        userID = null;

    }
}
}

Use Glide library and try to reduce the image file size. 使用Glide库并尝试减小图像文件的大小。 This will reduce/remove the lag u face on your device 这将减少/消除设备上的延迟

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM