在回收站视图中加载大量商品

时间:2017-06-03 19:38:27

标签: android android-recyclerview recycler-adapter android-glide mediastore

我在片段中有一个回收站视图,基本上我试图在回收站视图中加载歌曲列表。每行回收站视图都包含 imageview (用于专辑封面)和 textview (对于歌曲名称)。我遇到麻烦,当数据集的大小很大时,即当歌曲太多时,回收者视图滞后,应用程序最终给出ANR。我正在使用Glide在每行的imageview中加载专辑艺术。 谷歌音乐播放器如何能够毫不拖延地显示如此大量的歌曲?

修改 这是我的 SongsFragment

public class SongsFragment extends Fragment {
static {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
ProgressBar progressBar;    // progress bar to show after every 30 items
NestedScrollView nestedScrollView;  //for smooth scrolling of recyclerview as well as to detect the end of recyclerview
RecyclerView recyclerView;
ArrayList<Song> songMainList = new ArrayList<>();  //partial list in which items are added
ArrayList<Song> songAllList = new ArrayList<>(); //Complete List of songs
SongAdapter songsAdapter;
private LinearLayoutManager layoutManager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_songs, container, false);

    nestedScrollView = (NestedScrollView) rootView.findViewById(R.id.nestedScrollView);
    progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);

    String songJson = getActivity().getIntent().getStringExtra("songList");
    songAllList = new Gson().fromJson(songJson, new TypeToken<ArrayList<Song>>() {
    }.getType());
            //Getting list of all songs in songAllList

    if (songAllList.size() > 30) {  
        songMainList = new ArrayList<>(songAllList.subList(0,30));
    } else {
        songMainList = songAllList;
    }

    //if size of fetched songAllList>30 then add only 30 rows to songMainList

    recyclerView = (RecyclerView) rootView.findViewById(R.id.songs);
    int spanCount = 1; // 2 columns
    int spacing = 4; // 50px
    recyclerView.addItemDecoration(new GridItemDecoration(spanCount, spacing, true));
    recyclerView.setHasFixedSize(true);
    recyclerView.setNestedScrollingEnabled(false);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    songsAdapter = new SongAdapter(getActivity(), songMainList, recyclerView);

    nestedScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {
            View view = (View) nestedScrollView.getChildAt(nestedScrollView.getChildCount() - 1);
            int diff = (view.getBottom() - (nestedScrollView.getHeight() + nestedScrollView
                    .getScrollY()));

            if (diff == 0) {    //NestedScrollView scrolled to bottom
                progressBar.setVisibility(View.VISIBLE);    //show progressbar
                new Handler().postDelayed(new Runnable() { 
                    @Override
                    public void run() {
                        if (songMainList.size() < songAllList.size()) {
                            int x = 0, y = 0;
                            if ((songAllList.size() - songMainList.size()) >= 30) {
                                x = songMainList.size();
                                y = x + 30;
                            } else {
                                x = songMainList.size();
                                y = x + songAllList.size() - songMainList.size();
                            }
                            for (int i = x; i < y; i++) {
                                songMainList.add(songAllList.get(i));   //Adding new items from songAllList to songMainList one by one
                                songsAdapter.notifyDataSetChanged();
                            }
                        }
                        progressBar.setVisibility(View.GONE);
                    }
                }, 1500);


            }
        }
    });
    recyclerView.setAdapter(songsAdapter);


    return rootView;
    }
}

这是我的 RecyclerViewAdapter 以及 viewholder

public class SongAdapter extends RecyclerView.Adapter {

private List<Song> songsList;
private Context c;

private RecyclerView.ViewHolder holder;

public SongAdapter(Context context) {
    mainActivityContext = context;
}

public SongAdapter(Context context, List<Song> songs, RecyclerView recyclerView) {
    songsList = songs;
    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
    c = context;
}

public SongAdapter getInstance() {
    return SongAdapter.this;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.song_list_row, parent, false);
    return new SongViewHolder(view,c);
}

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

    if (holder instanceof SongViewHolder) {
        Song song = songsList.get(position);
        this.holder = holder;

        String name = song.getName();
        String artist = song.getArtist();
        String imagepath = song.getImagepath();

        ((SongViewHolder) holder).name.setText(name);

        ((SongViewHolder) holder).artist.setText(artist);

        if (!imagepath.equalsIgnoreCase("no_image")) //if the album art has valid  imagepath for this song

            Glide.with(c).load(imagepath)
                    .centerCrop()
                    .into(((SongViewHolder) holder).iv);
        else
            ((SongViewHolder) holder).iv.setImageResource(R.drawable.empty);

        ((SongViewHolder) holder).song = song;
    }
}

@Override
public int getItemCount() {
    return songsList.size();
}

static class SongViewHolder extends RecyclerView.ViewHolder{

    ImageView iv;
    TextView name, artist;
    CardView songListCard;
    private Context ctx;

    private OnLongPressListener mListener;

    SongViewHolder(View v, Context context) {
        super(v);
        this.ctx = context;
        iv= (ImageView) v.findViewById(R.id.album_art);
        name= (TextView) v.findViewById(R.id.name);
        artist= (TextView) v.findViewById(R.id.artist_mini);
        songListCard = (CardView) v.findViewById(R.id.song_list_card);
    }
}

当只有150-200件物品时,recyclerview工作正常,但当达到600-700件物品时,整个应用程序速度变慢。这可能是因为我在 onBindViewHolder 中使用滑行的方式?

5 个答案:

答案 0 :(得分:11)

排序答案:

LinearLayoutManager(context).apply { isAutoMeasureEnabled = false }
// or in Java
layoutManager.setAutoMeasureEnabled(false)

我们知道RecyclerView.LayoutManager#setAutoMeasureEnabled()的文件:

  

如果要支持WRAP_CONTENT,则此方法通常由LayoutManager调用,值为{@code true}

     

它的工作原理是在{@link RecyclerView#onMeasure(int,int)}调用期间调用{@link LayoutManager#onLayoutChildren(Recycler,State)},然后根据孩子的位置计算所需的维度。

如果我们设置mAutoMeasure = true,则会在LayoutManager#onLayoutChildren(Recycler, State)来电期间致电RecyclerView#onMeasure(int, int)。将调用每个子视图的onMeasure()方法,这会花费太多时间。

enter image description here

让我们看看LinearLayoutManager的构造函数

public LinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
    setOrientation(orientation);
    setReverseLayout(reverseLayout);
    setAutoMeasureEnabled(true);
}

所以,在我们设置mAutoMeasure = false之后,一切都会好的。

enter image description here

答案 1 :(得分:5)

通过在recyclerview上删除NestedScrollView解决了这个问题。 nestedscrollview不允许调用recyclerview.addOnScrollListener(),因为我在加载更多项目时遇到了延迟。 以下是我为RecyclerView实现loadOnScroll的方法 -

 recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (!recyclerView.canScrollVertically(1))
                onScrolledToBottom();
        }
    });

private void onScrolledToBottom() {
    if (songMainList.size() < songAllList.size()) {
        int x, y;
        if ((songAllList.size() - songMainList.size()) >= 50) {
            x = songMainList.size();
            y = x + 50;
        } else {
            x = songMainList.size();
            y = x + songAllList.size() - songMainList.size();
        }
        for (int i = x; i < y; i++) {
            songMainList.add(songAllList.get(i));
        }
        songsAdapter.notifyDataSetChanged();
    }

}

答案 2 :(得分:2)

您是否一次性加载数据? RecycleView应该没有问题,我认为如果你有太多的数据,处理本身可能会花费太多时间。您应该以块的形式加载数据并检查用户的滚动状态并加载下一批等等。有点像Instagram或Facebook这样做。

答案 3 :(得分:0)

晚上好,Naimish 我想到的唯一原因是您可能没有正确实施回收站视图。

请查看此项目作为良好实施的示例

https://github.com/google-developer-training/android-fundamentals/tree/master/RecyclerView

另外,为了学习目的,请查看这两本书并搜索有关回收者视图的章节。

https://google-developer-training.gitbooks.io/android-developer-fundamentals-course-practicals/ https://google-developer-training.gitbooks.io/android-developer-fundamentals-course-concepts/

答案 4 :(得分:0)

您可以使用 AndroidX Room & Paging 来实现这一点

  1. 将您的数据从网络缓存到本地 Room 数据库
  2. 使用 Paging 从 Room 数据库加载数据