因项目需要,在一个recyclerview的每个item中都加入了一个switch开关,用来控制某些设置项的功能
在代码初步完成后发现,第一个item中的开关会影响到后面所有的开关,而后面的开关会失效。
通过这篇文章,我找到了解决的办法,效仿其中的代码解决了自己的问题,以此为记录,方便以后查看
大致解决方法为:
private Boolean isBlueLightOn = KVUtils.getInstance().getBoolean(Setting.BLUE_LIGHT_MODE, false);
private Boolean isReadingModeOn = KVUtils.getInstance().getBoolean(Setting.READING_MODE, false);
private Boolean isDistanceOn = KVUtils.getInstance().getBoolean(Setting.DISTANCE, false);
private Boolean isLightProtectionOn = KVUtils.getInstance().getBoolean(Setting.LIGHT_PROTECTION, false);
private Boolean isTimeClockOn = KVUtils.getInstance().getBoolean(Setting.TIME_CLOCK, false);
private Boolean isEyesExercisesOn = KVUtils.getInstance().getBoolean(Setting.EYES_EXERCISES, false);
private Boolean[] switchPosition = new Boolean[6];
static class EyesViewHolder extends BaseViewHolder{
Switch mSwitch;
public EyesViewHolder(@NotNull View view) {
super(view);
this.mSwitch = view.findViewById(R.id.eyes_setting_switch);
}
}
//根据KV中取出的值初始化开关的状态
holder.mSwitch.setChecked(switchPosition[position]);
holder.mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
switch (position) {
case 0 :
break;
case 1 :
break;
case 2 :
break;
case 3 :
break;
case 4 :
break;
case 5 :
break;
default :
}
}
});