问题
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