【发布时间】:2019-11-26 12:01:04
【问题描述】:
背景颜色根据用户的喜好保存在数据库中。应用程序将根据每次打开时选择的背景颜色打开。我发现最好的方法是通过主题来完成。会有两个Styles.xml 文件中的主题。
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="selectedBackgroundColor">#fff</item>
</style>
<!-- Base application theme. -->
<style name="DarkTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="selectedBackgroundColor">#000</item>
</style>
</resources>
在.java中:
public void onCreate(Bundle savedInstanceState) {
if ( isUserSelectedBackground == true ) {
setTheme(R.style.DarkTheme);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
在activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/viewMain"
android:background="?attr/selectedBackgroundColor"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
错误: 错误:样式属性'attr/selectedBackgroundColor(又名 com.myapp:attr/selectedBackgroundColor)' 未找到。
但是这段代码不起作用。我该怎么办?
【问题讨论】:
-
尝试使用
R.style.DarkTheme而不是android.R.style.DarkTheme -
@sanoJ 真正的问题是我无法从 activity_main.xml 访问它。