android - 从 Xml 文件中访问样式中的项目
问题描述
背景颜色根据用户的喜好保存在数据库中。应用程序将在每次打开时根据所选的背景颜色打开。我发现最好的方法是通过主题来完成。将有两个主题在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(aka com.myapp:attr/selectedBackgroundColor)”。
但是这段代码不起作用。我该怎么办?
解决方案
您需要attrs.xml
在目录中有文件values
。将selectedBackgroundColor
attr 添加到此文件,如下所示。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="customAttr">
<attr name="selectedBackgroundColor" format="color"/>
</declare-styleable>
</resources>
推荐阅读
- python - Python中的For / While循环三角形不起作用
- ruby-on-rails - Rails 5:设计邀请的invited_by名称
- reactjs - componentDidMount 中未定义的道具
- java - How to properly serialize/deserialize java.time.DayOfWeek with Jackson?
- c# - 自引用的泛型参数
- typescript - 无法将 api 请求从 angular 应用程序发送到 API
- matlab - MATLAB中具有两个变量的函数的一阶和二阶偏导数
- java - 如何在 POST 中将 Base64 图像作为正文发送
- c++ - c++ 中允许从花括号值列表中分配 std::array 吗?
- sqlite - 安装cordova-sqlite-storage时出错