首页 > 解决方案 > 从 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)”。

但是这段代码不起作用。我该怎么办?

标签: androidxmlstyles

解决方案


您需要attrs.xml在目录中有文件values。将selectedBackgroundColorattr 添加到此文件,如下所示。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="customAttr">
        <attr name="selectedBackgroundColor" format="color"/>
    </declare-styleable>
</resources>

推荐阅读