我是安卓新手。 我试图创建一个简单的切换按钮并捕捉它的状态变化。但是当我在我的设备上运行它时它崩溃了。
这是 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>
我尝试在没有监听器对象的情况下运行此代码。(评论那些)但它给了我相同的结果。
最佳答案
您正在将开关转换为 Toggle Button,因此它会为您提供 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" />
关于java - 切换按钮不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22370899/