问题描述
setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// How to check whether the checkbox/switch has been checked
// by user or it has been checked programatically ?
if (isNotSetByUser())
return;
handleSetbyUser();
}
});
如何实现方法isNotSetByUser()
?
推荐答案
答案 2:
一个非常简单的答案:
使用 OnClickListener 而不是 OnCheckedChangeListener
Use on OnClickListener instead of OnCheckedChangeListener
someCheckBox.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// you might keep a reference to the CheckBox to avoid this class cast
boolean checked = ((CheckBox)v).isChecked();
setSomeBoolean(checked);
}
});
现在您只需选择点击事件,而不必担心程序化更改.
Now you only pick up click events and don't have to worry about programmatic changes.
答案 1:
我创建了一个包装类(参见装饰器模式),它以封装的方式处理这个问题:
I have created a wrapper class (see Decorator Pattern) which handles this problem in an encapsulated way:
public class BetterCheckBox extends CheckBox {
private CompoundButton.OnCheckedChangeListener myListener = null;
private CheckBox myCheckBox;
public BetterCheckBox(Context context) {
super(context);
}
public BetterCheckBox(Context context, CheckBox checkBox) {
this(context);
this.myCheckBox = checkBox;
}
// assorted constructors here...
@Override
public void setOnCheckedChangeListener(
CompoundButton.OnCheckedChangeListener listener){
if(listener != null) {
this.myListener = listener;
}
myCheckBox.setOnCheckedChangeListener(listener);
}
public void silentlySetChecked(boolean checked){
toggleListener(false);
myCheckBox.setChecked(checked);
toggleListener(true);
}
private void toggleListener(boolean on){
if(on) {
this.setOnCheckedChangeListener(myListener);
}
else {
this.setOnCheckedChangeListener(null);
}
}
}
CheckBox 仍然可以在 XML 中声明相同,但在代码中初始化 GUI 时使用它:
CheckBox can still be declared the same in XML, but use this when initializing your GUI in code:
BetterCheckBox myCheckBox;
// later...
myCheckBox = new BetterCheckBox(context,
(CheckBox) view.findViewById(R.id.my_check_box));
如果您想在不触发侦听器的情况下从代码中设置已检查,请调用 myCheckBox.silentlySetChecked(someBoolean)
而不是 setChecked
.
If you want to set checked from code without triggering the listener, call myCheckBox.silentlySetChecked(someBoolean)
instead of setChecked
.
这篇关于如何区分 Switch,Checkbox Value 是由用户更改还是以编程方式(包括保留)更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!