如何在我的风格中获得自己定义的属性值

Att*_*ers 17 resources android themes coding-style

我想使用自定义(自己)属性为对话框创建3个不同的主题.我想通过将其添加到主题的样式来设置标题颜色: <item name="titleColor">#FF0000</item>

我的themes.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyTheme" parent="@android:style/Theme">
    <item name="android:alertDialogStyle">@style/dialog</item>
</style>
<style name="MyRedTheme" parent="MyTheme">
    <item name="titleColor">#FF0000</item>
</style>
<style name="MyGreenTheme" parent="MyTheme">
    <item name="titleColor">#00FF00</item>
</style>
<style name="MyBlueTheme" parent="MyTheme">
    <item name="titleColor">#0000FF</item>
</style>
Run Code Online (Sandbox Code Playgroud)

我在attrs.xml中定义了titleColor属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <declare-styleable name="MyCustomAttributes">
  <attr name="titleColor" format="color|reference" />
 </declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)

我为对话框应用了一个主题.如何将titleColor属性的值传递给"android:color"属性?

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:custom="http://schemas.android.com/apk/res/com.dicare"
   android:shape="rectangle">
       <solid android:color="I want to pass titleColor value here"/>
</shape>
Run Code Online (Sandbox Code Playgroud)

Fun*_*onk 11

?titleColor 见这里

要么

您可以在colors.xml文件中定义颜色,并像普通资源一样引用它们:@ color/MyRed

您可以为自己的视图创建自定义属性,您可以从布局xmls中自定义该属性.例如,您可以扩展TextView以一种颜色(titleColor)写入第一行文本而不是文本的其余部分(android:textColor).

<color name="MyRed">#FF0000</color>

<style name="MyRedTheme" parent="MyTheme">
    <item name="titleColor">@color/MyRed</item>
</style>

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:custom="http://schemas.android.com/apk/res/com.dicare"
   android:shape="rectangle">
       <solid android:color="@color/MyRed"/>
</shape>
Run Code Online (Sandbox Code Playgroud)

  • 好 "?" 应该解决问题,但它给了我一个:java.lang.UnsupportedOperationException:无法转换为颜色:type = 0x2 (2认同)
  • 为什么接受这个解决方案.它是否回答了如何访问样式中定义的自己颜色的问题? (2认同)