android.widget.Switch不能强制转换为android.widget.ToggleButton



我得到这些简单的代码行:

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" />

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

应用程序编译并安装在我的Galaxy Nexus上,没有任何错误。然而,我在按下开关(on/off-slider)后立即得到这个异常:

android.widget。Switch不能强制转换为android.widget.togglebutton

有什么建议吗?

尽管SwitchToggleButtonCompoundButton,但Switch不是ToggleButton。两者不能互换使用。

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

尝试将类型转换改为(CompoundButton)(一般情况)或(Switch)(特定的,更好的)。

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

为什么要转换为切换按钮?只要继续使用switch对象。您只需要实现一个事件侦听器,就像您为按钮单击所做的那样。然后从布尔参数中获取检查状态。

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

相关内容

最新更新