现在要实现如下图功能(单选,选中任何一个没其他的全部要重置,看似checkbox,实则radiobutton,UI设计出来的,别问我radiobutton与checkbox有什么区别,我已经跟他们讲了~~~~):
遇到的问题:
1、java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling不能在RecyclerView计算layout或者滑动的时候使用 notifyDataSetChanged() 方法
尝试的方法:将notifyDataSetChanged()放到点击事件回调的单独UI线程里,但是也没用,会导致错乱,而且有时候点击会闪一下
解决方法:通过标志位来告诉layout是否当前还在计算计算layout
2、出现滑动的时候radiobutton选中错乱,明明选中了一个,但是在滑动的时候却显示在其他上面
适配器代码如下:
public class GiftAdapter extends SimpleRecAdapter<GiftModel, GiftAdapter.viewHolder> {
private static int TAG_VIEW = 0;
private String TAG = "GiftAdapter";
private HashMap<Integer, Boolean> states = new HashMap<>();
private boolean isBind;
public GiftAdapter(Context context) {
super(context);
}
@Override
public viewHolder newViewHolder(View itemView) {
return new viewHolder(itemView);
}
@Override
public int getLayoutId() {
return R.layout.item_gift;
}
@Override
public void setData(List<GiftModel> data) {
super.setData(data);
clearState();
}
@Override
public void onBindViewHolder(final viewHolder holder, final int position) {
final GiftModel giftModel = data.get(position);
isBind = true;
holder.tvGiftTitle.setText((position + 1) + "." + giftModel.getTitle());
holder.radioGift.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
clearState();
setCheckedState(position);
if (getRecItemClick() != null) {
getRecItemClick().onItemClick(position, giftModel, TAG_VIEW, holder);
}
if(!isBind){ //标识位
notifyDataSetChanged();
}
}
}
});
//注意setChecked与setOnCheckedChangeListener的顺序,同样会导致错乱
holder.radioGift.setChecked(states.get(position));
isBind = false;
}
private void clearState() {
for (int i = 0; i < getItemCount(); i++) {
states.put(i, false);
}
}
private void setCheckedState(int position) {
states.put(position, true);
}
public class viewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.tv_gift_title)
TextView tvGiftTitle;
@BindView(R.id.radio_gift)
RadioButton radioGift;
public viewHolder(View itemView) {
super(itemView);
KnifeKit.bind(this, itemView);
}
}
}
布局文件:R.layout.item_gift
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/ll_main_nav"
android:layout_width="match_parent"
android:layout_height="@dimen/list_line_normal_40"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_gift_title"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_vertical"
android:maxLines="1"
android:textColor="@color/white"
android:ellipsize="end"
android:text="这是礼品"/>
<RadioButton
android:id="@+id/radio_gift"
android:layout_width="@dimen/image_line_smaller"
android:layout_height="@dimen/image_line_smaller"
android:button="@drawable/custom_radio"
android:layout_marginLeft="@dimen/margin_largger"/>
</LinearLayout>