Android RecyclerView : notifyDataSetChanged() IllegalStateException

前端 未结 22 1847
天涯浪人
天涯浪人 2020-11-28 02:57

I\'m trying to update the items of a recycleview using notifyDataSetChanged().

This is my onBindViewHolder() method in the recycleview adapter.

@Over         


        
22条回答
  •  日久生厌
    2020-11-28 03:38

    You should move method 'setOnCheckedChangeListener()' to ViewHolder which is inner class on your adapter.

    onBindViewHolder() is not a method that initialize ViewHolder. This method is step of refresh each recycler item. When you call notifyDataSetChanged(), onBindViewHolder() will be called as the number of each item times.

    So If you notifyDataSetChanged() put into onCheckChanged() and initialize checkBox in onBindViewHolder(), you will get IllegalStateException because of circular method call.

    click checkbox -> onCheckedChanged() -> notifyDataSetChanged() -> onBindViewHolder() -> set checkbox -> onChecked...

    Simply, you can fix this by put one flag into Adapter.

    try this,

    private boolean onBind;
    
    public ViewHolder(View itemView) {
        super(itemView);
        mCheckBox = (CheckBox) itemView.findViewById(R.id.checkboxId);
        mCheckBox.setOnCheckChangeListener(this);
    }
    
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(!onBind) {
            // your process when checkBox changed
            // ...
    
            notifyDataSetChanged();
        }
    }
    
    ...
    
    @Override
    public void onBindViewHolder(YourAdapter.ViewHolder viewHolder, int position) {
        // process other views 
        // ...
    
        onBind = true;
        viewHolder.mCheckBox.setChecked(trueOrFalse);
        onBind = false;
    }
    

提交回复
热议问题