RecyclerView updates only on scroll

不羁岁月 提交于 2019-12-10 12:39:11

问题


I have a layout with a RecyclerView with the adapter:

public class SimpleRecyclerAdapter extends RecyclerView.Adapter<SimpleViewHolder> {

  protected List<JSONObject> data = new ArrayList<>();

  public List<JSONObject> getData() { return data; }
}     

I update it's adapter like:

public void udpdateFromJson( JSONObject payload ) {
  JSONArray msgs = payload.optJSONArray( "messages" );
  for( int ix = 0; null != msgs && ix < msgs.length(); ix++ ){
    JSONObject o = msgs.optJSONObject( ix );
    if( loadingMore ) adapter.getData().add( 1 + ix, o );
    else adapter.getData().add( o );
  }

  adapter.notifyDataSetChanged();
  recyclerView.invalidate();
}

The problem is, that I get to see the new item only when I touch or scroll the view.

What am I missing?

UPDATE:

to fix the problem I replaced the lines

adapter.notifyDataSetChanged();
recyclerView.invalidate();

with

adapter.notifyItemRangeInserted( loadingMore ? 1 : 0, msgs.length() );

and it worked


回答1:


try specifying the position of the item inserted or removed instead of notifyDataSetChanged();. you can use

notifyItemInserted(int pos);
notifyItemRangeChanged(int start, int end);`



回答2:


One possible solution is use Realm Adapter. Thant will manage your scroll view position based on insert/update/delete automatically. There is no flickering effects. Drawback is you have extend Object as Realm Object.




回答3:


As the question is already answered you can use one more line to scroll to the last position of your recyclerView using:

recyclerView.smoothScrollToPosition(msgs.length()-1)


来源:https://stackoverflow.com/questions/38140858/recyclerview-updates-only-on-scroll

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