java - 切换按钮以更改 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);
}
}
});
}
预期的结果是背景变化,但这并没有发生,并且应用程序在此之后崩溃
解决方案
请在此处使用约束布局
RelativeLayout currentLayout = (RelativeLayout) findViewById(R.id.main_layout);
而不是 RelativeLayout,因为您在 XML 文件中使用约束布局;)
推荐阅读
- c# - 如何使用包引用的绝对路径?
- ruby-on-rails - ruby on rails:带有散列的选择数组中的多个条件
- python - 如果作为 None 传递给函数,如何使用同名全局变量?
- python - 如何将单独的 Excel 工作表读入单独的 DataFrame?
- angular - Ngx-toastr、bootstrap 等库不适用于 angular.json 我该怎么办?
- python - 未能找到可以处理输入的数据适配器:
, - linux - 如何重命名文件夹中的所有文件 google colab
- bash - 将 vmlinux 重新打包到 zImage/bzimage
- android - Android 11 ADB - 通过 adb 停用电池选项/后台使用限制中的“将未使用的应用程序置于睡眠状态”选项
- nlp - 提取每个标记的隐藏表示 - PyTorch LSTM