切换按钮以更改 android 应用布局的背景颜色

Toggle button to change the background color of the layout of the android app

用于更改 Android 应用布局背景颜色的切换按钮

我正在尝试在 android 工作室中添加一个可以更改应用程序布局背景颜色的切换按钮

    public void perform_action(View v) {
        g = (ToggleButton) findViewById(R.id.toggleButton);
        g.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    RelativeLayout currentLayout = (RelativeLayout) findViewById(R.id.main_layout);
                    currentLayout.setBackgroundColor(Color.RED);
                } else {
                    RelativeLayout currentLayout = (RelativeLayout) findViewById(R.id.main_layout);
                    currentLayout.setBackgroundColor(Color.BLACK);
                }
            }
        });
    }

预期的结果是背景发生变化,但这并没有发生,应用程序在此之后崩溃

这里请使用约束布局 RelativeLayout currentLayout = (RelativeLayout) findViewById(R.id.main_layout); 而不是 RelativeLayout 因为您在 XML 文件中使用了约束布局 ;)

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

您必须在两个文件中同时使用相同的布局。因此,将 XML 文件布局更改为 RelativeLayout 而不是 ConstraintLayout 或在 Java 文件 ConstraintLayout 的 RelativeLayout 中更改 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);