可以从styles.xml文件中引用属性吗?

3
我希望用户能够在我的整个应用中切换颜色皮肤。我的意思是,当用户按下屏幕上的按钮时,动态地切换应用程序某些自定义视图的样式。我知道如果在onCreate()方法之前调用Activity.setTheme(),你可以动态地改变应用程序的主题,但普通视图(例如NavigationView)应用于其xml布局的自定义样式没有设置setThemesetStyle方法,因此似乎不可能动态地改变它们的样式。

我认为实现我的目标可以引用在styles.xml文件中声明的AppTheme中声明的颜色。我的意思是,我可以声明两个AppThemes,每个都有一组颜色,然后,在为自定义视图声明的自定义样式中引用这些颜色。类似于以下内容:

<resources>
    <style name="AppTheme" parent="Theme.AppCompat">
        <item name="customColor">#111111</item>
    </style>

    <style name="AppTheme.AnotherColor" parent="Theme.AppCompat">
        <item name="customColor">#222222</item>
    </style>

    <style name="CustomActionBar">
        <!-- title text color -->
        <item name="android:textColorPrimary">@styles/customColor</item>
    </style>
</resources>

因此,按默认情况下,“AppTheme”上声明的自定义颜色将默认应用,使用颜色111111。但是当我使用setTheme(R.styles.AppTheme_AnotherColor)更改应用程序的主题时,应用的颜色将为222222。如果这是可能的,那就太完美了!但不可能或者我不知道如何直接从同一styles.xml文件中的另一个样式中访问已声明的颜色。我的意思是@styles/customColor是不正确的,我不知道如何访问该颜色。
如何实现这一点?

自定义属性使用?attr/customAttributeName进行引用,因此在您的情况下,您需要在CustomActionBar主题中放置?attr/customColor - TR4Android
你在 attrs.xml 文件中定义了吗?每个自定义属性都需要在那里定义,以便可以找到它。在该文件中放置类似 <resources><attr name="customColor" format="color"/></resources> 的内容。 - TR4Android
是的,我已经在我的一个应用程序中使它工作了。不过,在安卓上,主题和样式有时可能会很难搞定... - TR4Android
让我们在聊天中继续这个讨论 - NullPointerException
@TR4Android请接受我之前发出的两条消息中的聊天邀请。 - NullPointerException
显示剩余8条评论
1个回答

8

是的,添加自定义属性和颜色到主题中是完全可能的。需要做以下步骤:

  1. Define your custom attribute in your res/values/attrs.xml file:

    <resources>
        <attr name="customColor" format="color" />
    </resources>
    
  2. Define the attribute's value in your themes:

    <style name="AppTheme" parent="Theme.AppCompat">
        <item name="customColor">#111111</item>
    </style>
    
    <style name="AppTheme.AnotherColor" parent="Theme.AppCompat">
        <item name="customColor">#222222</item>
    </style>
    
  3. Use your custom attribute in your styles:

    <style name="CustomActionBar">
        <!-- title text color -->
        <item name="android:textColorPrimary">?attr/customColor</item>
    </style>
    

非常感谢。是否可以使用Java代码编写自定义XML属性(在attrs.xml中创建)的值? - NullPointerException
不容易。安卓主题和样式真的是最不灵活的事情之一。你可以在这里找到一些提示:https://dev59.com/AVsX5IYBdhLWcg3wS9_o#34178187。 - TR4Android
TR4Android 能否在小部件中使用颜色?小部件没有主题,因此无法通过设置小部件的主题来设置属性的值...必须有其他方法。 - NullPointerException
很遗憾,我没有使用小部件的经验,但你可以尝试使用类似android:background="?attr/customColor"这样的东西。 - TR4Android

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接