Fabian
Fabian

Reputation: 778

android.widget.Switch cannot be cast to android.widget.ToggleButton

I got these simple lines of code:

MainActivity:

public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
(...)
   public void VehicleDeleteModus(View v){
    boolean on = ((ToggleButton) v).isChecked();
   (...)
   }
}

XML:

<Switch
    android:id="@+id/switch1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="VehicleDeleteModus"
    android:paddingLeft="12dp"
    android:text="Delete-Modus"
    android:textColor="#ffffff" />

source: http://developer.android.com/guide/topics/ui/controls/togglebutton.html

The app compiles and gets installed on my Galaxy Nexus without any errors. However, I get this exception immediately after pressing the switch (on/off-slider):

android.widget.switch cannot be cast to android.widget.togglebutton

Any suggestions?

Upvotes: 0

Views: 2297

Answers (2)

Andrew T.
Andrew T.

Reputation: 4707

Even though Switch and ToggleButton are CompoundButton, Switch is not a ToggleButton. Each one cannot be used interchangeably.

         CompoundButton
                |
    +-----------+----------+
    |                      |
 Switch               ToggleButton

Try changing the casting to (CompoundButton) (for general case) or (Switch) (specific, better) instead.

public void VehicleDeleteModus(View v){
    boolean on = ((Switch) v).isChecked();
    (...)
}

Upvotes: 1

sean1588
sean1588

Reputation: 1

Why are you wanting to cast to a toggle button? Just keep using the switch object. You just have to implement an event listener, just like you would for a button click.Then get the checked status from the boolean parameter.

switch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    //get boolean value from parameter.

    boolean on = isChecked;
    }
});

Upvotes: 0

Related Questions