简体   繁体   中英

Check state of togglebutton android

Im new to android and I don't get the code on the developers website about this really, I just want to check if the state of the toggle button is on or off. I have the following scenario

if (isCheckedToggleButton?)
{
    // do something         
}
else
{
    // do something else
}

And a method as the guide suggests

public void onToggleClicked(View view)
{
    boolean on = ((ToggleButton)view).isChecked();

    if(on) {
        return;
    } else {

    }
}

So I just want to see if the toggle button is on or off so I can decide whether to execute the code inside the if or the else. Unfortunately the method provided by the android guide is a void so it doesn't return a boolean. How can I still check the state?

        <Switch
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Lift"
            android:textOff="Uit"
            android:textOn="Aan"
            android:id="@+id/switchLift" android:layout_below="@id/btnEindpunt"
            android:layout_alignLeft="@+id/btnEindpunt"/>

Use it like this

myToggleButton.setOnCheckedChangeListener( new OnCheckedChangeListener()
{
    @Override
    public void onCheckedChanged(CompoundButton toggleButton, boolean isChecked)
    {
        if(isChecked)
            // Do something
        else
           // Do the other thing
    }
});

Change

ToggleButton myToggleButton = ((ToggleButton) findViewById(R.id.switchLift));

to

Switch myToggleButton = ((Switch) findViewById(R.id.switchLift));

Also change isChecked to something else like mIsChecked or inside the listener use YourClassName.this.isChecked for changing its value. There is already a local variable with same name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM