当在设置 setOnCheckedChangeListener
之后调用 setChecked
方法会触发 setOnCheckedChangeListener
监听.
解决方案
- 判断按钮是否被人按下.
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!buttonView.isPressed()) {
return;
}
doSomeThing();
}
});
此问题参考StackOverFlow(http://stackoverflow.com/questions/9129858/how-can-i-distinguish-whether-value-is-changed-by-user-or-programmatically-incl)
- 在设置之前取消监听,设置后添加监听.
mSwitch.setOnCheckedChangeListener(null);
mSwitch.setChecked(true);
mSwitch.setOnCheckedChangeListener(mListener);