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(this.myListener == 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);
}
}
复选框仍然可以宣布XML是相同的,但在code初始化你的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));
如果你想设置从code检查,而不触发听者代替,调用 myCheckBox.silentlySetChecked(someBoolean)
setChecked
。
If you want to set checked from code without triggering the listener, call myCheckBox.silentlySetChecked(someBoolean)
instead of setChecked
.
上一篇:的Android如何喜欢与Facebook 3.0 SDK后喜欢、oid、Andr、SDK
下一篇:无法链接使用Eclipse进行Android的OSX上到cocos2dx上到、链接、Eclipse、Android