0

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?

Andrew T.
  • 4,701
  • 8
  • 43
  • 62
Fabian
  • 748
  • 2
  • 11
  • 20
  • 1
    You mean convert to `CompoundButton` not `ToggleButton`. Casting `Dog` to `Cat` is not possible – Glenn May 15 '14 at 02:20

2 Answers2

1

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();
    (...)
}
Andrew T.
  • 4,701
  • 8
  • 43
  • 62
0

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;
    }
});