【问题标题】:Accessing Item in Style From Xml File从 Xml 文件中访问样式中的项目
【发布时间】: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 访问它。

标签: android xml styles


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-01
    • 2019-11-11
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多