首页 > 解决方案 > 切换按钮以更改 android 应用程序布局的背景颜色

问题描述

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

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

    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);
                }
            }
        });
    }

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

标签: javaandroidtogglebutton

解决方案


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


推荐阅读