Java 切换按钮更改android应用程序布局的背景色

Java 切换按钮更改android应用程序布局的背景色,java,android,togglebutton,Java,Android,Togglebutton,切换按钮更改Android应用程序布局的背景色 我试图在android studio上添加一个切换按钮,可以更改应用程序布局的背景颜色 公共无效执行(u actionView v){ g=ToggleButton findViewByIdR.id.ToggleButton; g、 SetOnCheckedChangeListener新建复合按钮。OnCheckedChangeListener{ public void onCheckedChangedCompoundButton按钮视图,布尔值已

切换按钮更改Android应用程序布局的背景色

我试图在android studio上添加一个切换按钮,可以更改应用程序布局的背景颜色

公共无效执行(u actionView v){ g=ToggleButton findViewByIdR.id.ToggleButton; g、 SetOnCheckedChangeListener新建复合按钮。OnCheckedChangeListener{ public void onCheckedChangedCompoundButton按钮视图,布尔值已选中{ 如果我检查过{ RelativeLayout currentLayout=RelativeLayout findViewByIdR.id.main\u布局; currentLayout.setBackgroundColorColor.RED; }否则{ RelativeLayout currentLayout=RelativeLayout findViewByIdR.id.main\u布局; currentLayout.setBackgroundColorColor.BLACK; } } }; }
预期的结果是背景变化,但这不会发生,应用程序在此之后崩溃。请在此处使用约束布局 RelativeLayout currentLayout=RelativeLayout findViewByIdR.id.main\u布局;而不是RelativeLayout,因为您在XML文件中使用约束布局

根据您的crush报告:您正在XML文件中使用ConstraintLayout。另一方面,您正在初始化Java文件中的RelativeLayout

您必须在两个文件中同时使用相同的布局。因此,将XML文件布局更改为RelativeLayout而不是ConstraintLayout,或者在RelativeLayout的Java文件ConstraintLayout中更改ConstraintLayout

请记住,两种布局应该是相同的

希望它能帮助你


谢谢你

一旦我改为布局来约束,它就工作得很好了

if (isChecked) {
                ConstraintLayout currentLayout = (ConstraintLayout) findViewById(R.id.main_layout);
                currentLayout.setBackgroundColor(Color.RED);
            } else {
                ConstraintLayout currentLayout = (ConstraintLayout) findViewById(R.id.main_layout);
                currentLayout.setBackgroundColor(Color.BLACK);

您能给我们看一下您的错误日志吗?您的崩溃报告是什么?10519-10519/com.example.crt D/AndroidRuntime:关闭VM 10519-10519/com.example.crt E/AndroidRuntime:致命异常:主进程:com.example.crt,PID:10519 java.lang.ClassCastException:android.support.constraint.ConstraintLayout不能在com.example.crt.MainActivity$2.onCheckedChangedMainActivity.java:94在android.widget.CompoundButton.setCheckedCompoundButton.java:171在android.widget.ToggleButton.setCheckedToggleButton.java:71位于android.widget.CompoundButton.TogglecompoundButton可能您正在XML文件中使用ConstraintLayout,但您正在java文件中初始化RelativeLayout。您必须使用相同的布局。您能给我们XML文件代码吗?将布局更改为constraint,效果很好。如果您能得到我的帮助,我将不胜荣幸。