问题
I am trying to remove an item from my RecyclerView
, but I always get an error.
java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling
I am using notifyDataSetChanged()
. How can I solve this?
Here is my adapter code
public class ListAdapters extends RecyclerView.Adapter<ListAdapters.MyViewHolder> {
public ArrayList<String> tvdatalist;
Context c;
int pos;
ListAdapters.MyViewHolder myViewHolder;
private LayoutInflater layoutInflater;
int[] arr;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public EditText edttxt;
public CheckBox cb;
public MyViewHolder(View view) {
super(view);
edttxt = (EditText) view.findViewById(R.id.edttxt);
cb = (CheckBox) view.findViewById(R.id.cb);
}
@Override
public void onClick(View v) {
}
}
public ListAdapters(Context c, ArrayList<String> tvdatalist) {
this.c = c;
this.layoutInflater = LayoutInflater.from(c);
this.tvdatalist = tvdatalist;
arr = new int[tvdatalist.size()];
for (int i = 0; i < 20; i++) {
arr[i] = 0;
}
}
@Override
public ListAdapters.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ListAdapters.MyViewHolder(this.layoutInflater.inflate(R.layout.list_ittm, parent, false));
//return new LandingPageAdapter.MyViewHolder(itemView);
}
public void onBindViewHolder(final ListAdapters.MyViewHolder holder, final int position) {
myViewHolder = holder;
final String ShowsBean = tvdatalist.get(position);
myViewHolder.edttxt.setText(ShowsBean);
if (arr[pos] == 0) {
myViewHolder.cb.setChecked(false);
myViewHolder.edttxt.setKeyListener(null);
} else {
myViewHolder.cb.setChecked(true);
myViewHolder.edttxt.setFocusable(true);
}
myViewHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (arr[position]==0){
arr[position]=1;
}else{
arr[position]=0;
}
notifyDataSetChanged();
}
});
}
@Override
public int getItemCount() {
return tvdatalist.size();
}
public interface ItemClickListener {
void onClick(View view, int position, boolean isLongClick);
}
}
回答1:
As Abbas said
This usually occurs when you are calling notify on bg thread. So just move notify to ui thread
else you can use notifyItemChanged(position);
this will also worked as well.
回答2:
This problem shows when you are trying to update the recyclerview when it still inflating the item, try to move the notifyItemChanged(position), to where you are sure the item has been added to your view before calling the- method(notifyItemChanged(position));
回答3:
You can also use runnable to make changes on UI thread.
recyclerView.post(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
This will notify adapter changes on UI thread.
来源:https://stackoverflow.com/questions/45324815/illegalstateexception-cannot-call-this-method-while-recyclerview-is-computing-a