简体   繁体   中英

Why does wrapping my RecyclerView adapter in another class cause different behaviour?

I have come across an issue when using RecyclerViews. Basically during the initial load of a RecyclerView (after I start an activity) there is a small delay before items appear.

After experimenting for a while I found a way to remove this delay by wrapping my adapter in another class as follows:

public class AdapterWrapper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private RecyclerView.Adapter<RecyclerView.ViewHolder> mAdapter;

    public AdapterWrapper(RecyclerView.Adapter<RecyclerView.ViewHolder> adapter) {
        mAdapter = adapter;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return mAdapter.onCreateViewHolder(parent, viewType);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        mAdapter.onBindViewHolder(holder, position);
    }

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

    @Override
    public int getItemViewType(int position) {
        return mAdapter.getItemViewType(position);
    }
}

Then in my activity I have this:

protected void onCreate(Bundle savedInstanceState) {
    ...
    setUpRecyclerView();
    ...
}

public void setUpRecyclerView() {
    mAdapter = new MyAdapter(this, mCursor);
    mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    //mRecyclerView.setAdapter(mAdapter);                   // This causes a small delay.
    mRecyclerView.setAdapter(new AdapterWrapper(mAdapter)); // This doesn't
}

This seems really weird to me and I have no idea why the behaviour is different. Has anybody got any potential theory to explain this?

Extra information:
-I'm using a cursor loader to provide data to my adapter.
-My adapter is subclassed using a CursorRecyclerAdapter found at http://quanturium.github.io

You have to override every method, not just implement the abstract methods.

When you call your overriden methods on AdapterWrapper it's getting passed to the wrapped object. Every other method is going to your wrapper and not getting passed on.

If im right, your premise may be a red herring. Delays like this can be—and usually are—because you are performing updates to the ui from a background thread.

We had a similar issue and finally tracked it dowm to that being rhe case. Moving the code back to the main thread, everything became instant again.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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