user3764694
user3764694

Reputation:

Why doesn't the isEnabled for the ToggleButton work in Android?

I just defined a ToggleButton variable, found the view by the id, set activated to false, and set a OnClickListener. In the onClick method, I checked if it was enabled in a if statement. If it was enabled, then it should have logged it, but I checked in Console and LogCat, and it didn't display anything. Here's my code:

tb = (ToggleButton) findViewById(R.id.onoff);
    tb.setActivated(false);
    tb.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if(tb.isEnabled()){
                Log.d("", "activated");
            }else if(!tb.isEnabled()){
                Log.d("", "deactivated");
            }
        }
    });

I don't know how to do the 'code inside text' thing (like onClick should have a gray box over it).

Upvotes: 0

Views: 1375

Answers (1)

Akshay Deo
Akshay Deo

Reputation: 528

 public boolean isEnabled ()

This method is inherited from base class view, which mostly defines whether it is user intractable or not.

You will need to use isChecked() method to determine whether ToggleButton is on or off.

Update your code as:

tb = (ToggleButton) findViewById(R.id.onoff);
tb.setActivated(false);
tb.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        if(((ToggleButton)v).isChecked()){
            Log.d("", "activated");
        }else{
            Log.d("", "deactivated");
        }
    }
});

or second way

in your xml code

<ToggleButton 
android:id="@+id/togglebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Vibrate on"
android:textOff="Vibrate off"
android:onClick="onToggleClicked"/>

in your activity

public void onToggleClicked(View view) {
// Is the toggle on?
boolean on = ((ToggleButton) view).isChecked();

if (on) {
    // Enable vibrate
} else {
    // Disable vibrate
}
}

Upvotes: 1

Related Questions