Reputation: 4419
I've a Switch with a listener:
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
}
Doing:
mSwitch.setChecked(false);
has no effect, callback is not triggered. Instead like this:
mSwitch.setChecked(true);
mSwitch.setChecked(false);
works as expected. Am I doing something wrong? If the checkbox state is false and one use setChecked(false), the normal behaviour is to skip callback? Or is it a bug?
Upvotes: 4
Views: 13611
Reputation: 1
in kotlin
override fun onStart() {
super.onStart()
mSwitch.setChecked(false)
}
Upvotes: 0
Reputation: 2780
No it's not a bug, is the normal behavior.
If you look the code of the CompoundButton you can see
/**
* <p>Changes the checked state of this button.</p>
*
* @param checked true to check the button, false to uncheck it
*/
public void setChecked(boolean checked) {
if (mChecked != checked) {
mChecked = checked;
refreshDrawableState();
notifyViewAccessibilityStateChangedIfNeeded(
AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
// Avoid infinite recursions if setChecked() is called from a listener
if (mBroadcasting) {
return;
}
mBroadcasting = true;
if (mOnCheckedChangeListener != null) {
mOnCheckedChangeListener.onCheckedChanged(this, mChecked);
}
if (mOnCheckedChangeWidgetListener != null) {
mOnCheckedChangeWidgetListener.onCheckedChanged(this, mChecked);
}
mBroadcasting = false;
}
}
Where mChecked
is the actual value of the switch.
If you want to trigger every time simple override onClick listener like this
mSwitch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Is checked? "+mSwitch.isChecked(), Toast.LENGTH_SHORT).show();
}
});
Upvotes: 1
Reputation: 780
The callback will be called only when you defined your listener and afterwords try to change it by setChecked(false/true)
Upvotes: 0
Reputation: 12963
It will be Called when the checked state of a compound button has changed.
So if its state is already false it won't be called when you call false.
Upvotes: 1