gpt4 book ai didi

android - 当 RecyclerView 正在计算布局或滚动尝试从 recyclerview 中删除项目时无法调用此方法

转载 作者:IT老高 更新时间:2023-10-28 22:16:42 25 4
gpt4 key购买 nike

我正在尝试从 recyclerview 中删除我的项目,但我总是收到错误

java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling

我正在使用通知数据集已更改,我可以解决这个问题吗?

public class AdapterIntransit extends RecyclerView.Adapter<AdapterIntransit.ViewHolder> {
private Context context;
List<DataIntransit> data;

public AdapterIntransit(Context context, List<DataIntransit> data) {
this.context = context;
this.data = data;
}

@Override
public AdapterIntransit.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardintransit, parent, false);
return new ViewHolder(itemView);
}

@Override
public void onBindViewHolder(AdapterIntransit.ViewHolder holder, int position) {
if (data.get(position).getJml1() - data.get(position).getJml2() <= 0) {
data.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, getItemCount());
notifyDataSetChanged();
} else {
holder.kode.setText(data.get(position).getKode());
holder.nama.setText(data.get(position).getNama());
holder.jumlah.setText(String.valueOf(data.get(position).getJml1() - data.get(position).getJml2()));
}
}

@Override
public int getItemCount() {
return data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView kode, nama, jumlah;
public ViewHolder(View itemView) {
super(itemView);
kode = (TextView)itemView.findViewById(R.id.kode);
nama = (TextView)itemView.findViewById(R.id.nama);
jumlah = (TextView)itemView.findViewById(R.id.jumlah);

}
}
}

最佳答案

以下答案对我有用

这只是问题的workaround

这通常发生在您在 background thread 上调用 notifyDataSetChanged() 时。所以只需将通知移动到 UI 线程

recyclerView.post(new Runnable()
{
@Override
public void run() {
myadapter.notifyDataSetChanged();
}
});

You use your RecyclerView instance and inside the post method a new Runnable added to the message queue. The runnable will be run on the user interface thread. This is a limit for Android to access the UI thread from background (e.g. inside a method which will be run in a background thread).for more you run it on UI thread if you needed.

如果需要,您可以在 UI 线程上运行它

 runOnUiThread(new Runnable(){
public void run() {
// UI code goes here
}
});

关于android - 当 RecyclerView 正在计算布局或滚动尝试从 recyclerview 中删除项目时无法调用此方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43221847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com