gpt4 book ai didi

java - 切换按钮不工作

转载 作者:行者123 更新时间:2023-11-29 05:26:55 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com