tony9099
tony9099

Reputation: 4727

trigger CheckedChanged programmatically for toggleButton (CompoundButton)

How can I trigger programmatically the following method : (without clicking/swiping the on/off toggle switch)

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
  //randomness
}

I figured an alternative way would be, calling

switch1.setChecked(true);

Then doing a manual check.

Upvotes: 3

Views: 2100

Answers (2)

Mavelo
Mavelo

Reputation: 1259

There actually is a way of calling it if you refer to the class methods ;)

ToggleButton t = (ToggleButton) findViewById(R.id.myToggle); t.performClick();

See http://developer.android.com/reference/android/widget/CompoundButton.html#performClick()

Upvotes: 3

chdorner
chdorner

Reputation: 531

There is no way of calling the onCheckedChanged of a CompoundButton (ToggleButton or Switch) like this.

However, I see two other solutions:

  1. Keep the listener object around and manually calling the onCheckedChanged function with the button and the boolean.
  2. Abstract the logic inside the CompoundButton.OnCheckedChangedListener implementation into another function that you can call manually.

Upvotes: 0

Related Questions