Recyclerview Position changing to first position when I Update

孤人 提交于 2019-12-11 00:18:10

问题


I am using onLoadMoreListener when i scroll RecyclerView. It will update the RecyclerView data when you scroll to bottom. After updating the Recyclerview data. The Recyclerview goes back up to the top. Ideally, I would like to retain the position in the RecyclerView. Any thoughts on how I should go about doing this?

mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
              new GroupData().execute();
            }
        });


InnerClass

    public static class GroupData extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... voids) {
           try{
             GroupList gm = new GroupList();
             .....
             groupvalues.add(gm);
            } catch (Exception e){
               Log.d("Grouplist ", e.toString());
           }
          return null;
        }
        @Override
        protected void onPostExecute(Void aVoid) {
             super.onPostExecute(aVoid);
             mAdapter = new GroupAdapter(groupvalues,mrecyclerview);
             mrecyclerview.setAdapter(mAdapter);
             progressDialog.dismiss();
             mAdapter.notifyDataSetChanged();
             }
           }
         }

回答1:


Try this,

public static class GroupData extends AsyncTask<Void, Void, Void> {
    int size = 0;

    @Override
    protected void onPreExecute() {
        size = groupvalues.size();
    }

    @Override
    protected Void doInBackground(Void... voids) {
        try {
            GroupList gm = new GroupList();
            .....
            groupvalues.add(gm);
        } catch (Exception e) {
            Log.d("Grouplist ", e.toString());
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        mAdapter.notifyItemRangeChanged(size, groupvalues.size() - size);
        progressDialog.dismiss();
    }
}



回答2:


When you are loading you must be knowing the position of top element of new loaded items. just call:

recyclerView.scrollToPosition(position);

or just save the last know position of your recyclerView and Scroll to that position when you load more items




回答3:


Just notify your adapter in onPostExecute. No need to initialise your adapter again.

    @Override
    protected void onPostExecute(Void aVoid) {
         super.onPostExecute(aVoid);
         progressDialog.dismiss();
         mAdapter.notifyDataSetChanged();
    }

Initialise your adapter in onCreate

mAdapter = new GroupAdapter(groupvalues,mrecyclerview);
mrecyclerview.setAdapter(mAdapter);


来源:https://stackoverflow.com/questions/41776696/recyclerview-position-changing-to-first-position-when-i-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!