我试图查看其他答案,但他们没有解决我的问题。每次我想在recyview中加载项目并且无休止地滚动时,我的recyclelerview会出现错误。有时它会将项目加载到recyclerview,有时它会将回收视图留空,并在logcat上给出一条消息,如下所示。
IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling
我的申请类是
itemAdapter.setOnLoadMoreListener(new Schoolarship_Adapter.OnLoadMoreListener() {
@Override
public void onLoadMore() {
listItem.add(null);
itemAdapter.notifyItemInserted(listItem.size() - 1);
final Handler handler = new Handler();
final Runnable r = new Runnable() {
@Override
public void run() {
listItem.remove(listItem.size() - 1);
itemAdapter.notifyItemRemoved(listItem.size());
++pagenumber;
new RetrieveItems().execute();
System.out.println("working now i guess");
itemAdapter.notifyDataSetChanged();
itemAdapter.setLoaded();
}
};
handler.post(r);
}
});
我的适配器看起来像
Schoolarship_Adapter(Context cont, List<Schoolarship> items, @NonNull RecyclerView rv){
context = cont;
listItems = items;
if((rv.getLayoutManager() instanceof LinearLayoutManager)) {
final LinearLayoutManager gm = (LinearLayoutManager) rv.getLayoutManager();
rv.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy){
super.onScrolled(recyclerView, dx, dy);
totalItemCount = gm.getItemCount();
lastVisibleItem = gm.findLastVisibleItemPosition();
if(!loading &&totalItemCount <= (lastVisibleItem + visibleThreshold)){
if(onLoadMoreListener!=null){
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
请问,为什么每次运行此应用程序时仍然会出现错误?
答案 0 :(得分:0)
原因是,你的onLoadMore() 它会在添加/加载新项目时计算recyclerView的高度,所以当你给notifyDataSetChanged它肯定会抛出异常。 也许这会起作用
protected void postAndNotifyAdapter(final Handler handler, final RecyclerView recyclerView, final RecyclerView.Adapter adapter) {
handler.post(new Runnable() {
@Override
public void run() {
if (!recyclerView.isComputingLayout()) {
adapter.notifyDataSetChanged();
} else {
postAndNotifyAdapter(handler, recyclerView, adapter);
}
}
});
}