java - 切换按钮不工作

标签 java android togglebutton

我是安卓新手。 我试图创建一个简单的切换按钮并捕捉它的状态变化。但是当我在我的设备上运行它时它崩溃了。

这是 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/

相关文章:

wpf - 为什么在触发 MouseOver 状态后 Checked 状态的 ColorAnimation 不保留颜色?

java - 将接口(interface)的类​​信息存储在 HashMap 中,并稍后创建该接口(interface)的实例

android - 如何在android中使用相机检查图像是在纵向模式还是横向模式下捕获的?

JavaScript : validate price with some constraints

android - 每次程序启动时可绘制对象的显示分辨率密度减半

android - 如何将文本设置为切换按钮上图像的右侧

c# - WPF ToggleButton 模板 BorderBrush

java - 配置activemq的授权

java - 延迟初始化注入(inject)的 bean 依赖项(Spring 3)

java - 内联图像与临时文件(Java XHTML->PDF 生成)