我是机器人新手。我尝试创建一个简单的切换按钮并捕捉它的状态变化。但当我在我的设备上运行它时它就崩溃了。
以下是MainActivity.java代码:
package com.example.addimagebutton;
import android.os.Bundle;
import android.app.Activity;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
private ToggleButton tbSwitch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tbSwitch = (ToggleButton) findViewById(R.id.swButton);
tbSwitch.setOnCheckedChangeListener(toggleListener);
}
OnCheckedChangeListener toggleListener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
Toast.makeText(getApplicationContext(), "On",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Off",
Toast.LENGTH_SHORT).show();
}
}
};
}以下是activity_main.xml代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Switch
android:id="@+id/swButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Switch"
android:textOff="Off"
android:textOn="On" />
</LinearLayout>我试图在没有监听器对象的情况下运行这段代码。(注释这些),但是它给了我同样的结果。
发布于 2014-03-13 06:40:33
您正在切换到按钮,因此它给您ClassCastException..。
改变这个
<Switch
android:id="@+id/swButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Switch"
android:textOff="Off"
android:textOn="On" />转到
<ToggleButton
android:id="@+id/swButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Switch"
android:textOff="Off"
android:textOn="On" />发布于 2014-03-13 06:40:51
使用ToggleButton而不是Switch
<ToggleButton
android:id="@+id/swButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Switch"
android:textOff="Off"
android:textOn="On"" />因为您的布局包含Switch并使用ToggleButton进行转换。那是不对的
发布于 2014-03-13 06:41:17
将switch更改为ToggleButton
<ToggleButton
android:id="@+id/swButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Switch"
android:textOff="Off"
android:textOn="On" />https://stackoverflow.com/questions/22370899
复制相似问题