Android : 在 styles.xml 中创建您自己的属性名称

Android : Create your own attribute names in styles.xml

我需要一些帮助,我已经浏览了一段时间,但是我找到的 none 主题可以解决我的问题。希望你能帮助我!

开始吧:我有一个自定义视图,我们称它为 CustomView。 它也有一些自定义属性,在 attrs.xml 文件中定义,如下所示:

<declare-styleable name="CustomView">
    <attr name="customBackgroundColor" format="color"/>
    <attr name="customTextColor" format="color"/>
    <attr name="customWhatever" format="dimension"/>
</declare-styleable>

此视图是我要创建的库的一部分,因此我可以在多个项目中使用它。

有趣的部分来了:实际上,我会经常使用这个视图,所以我想在 styles.xml 中定义一个样式来定义它的 属性,所以我没有进入我使用此视图编辑其属性的每个 xml 布局文件。像这样:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="customViewStyle">@style/myCustomViewStyle</item>
</style>

<style name="myCustomViewStyle" parent="CustomViewStyle">
    <item name="customBackgroundColor">@color/red</item>
    <item name="customTextColor">@color/blue</item>
    <item name="customWhatever">@dimen/someHeight</item>
</style>

所以我的问题是:如何定义这个 "customViewStyle" 密钥,如果可能的话,如何从中获取信息?

奖金:我已经能够通过这样做创建这个 "customViewStyle" 密钥:

<attr name="customViewStyle" format="reference"/>

但我还没有找到如何利用它。

How do I define this "customViewStyle" key?

<attr name="customViewStyle" format="reference"/>在任何 <declare-styleable> 标签之外

But I haven't found yet how to exploit it.

创建具有所需属性的样式。您已经在 post 中使用 MyCustomViewStyle 条目完成了该操作,但是您已经为它提供了一个不存在的父样式(据我所知)。我可能会使用 `parent="android:Widget" 除非其他更合适。

我假设您的自定义视图 class 已经使用 TypedArray:

从 XML 读取属性
TypedArray a = context.obstainStyleAttributes(attrs, R.styleable.CustomView,
        R.attr.customViewStyle, 0);

将最后一个参数替换为您刚刚定义的默认样式:

TypedArray a = context.obstainStyleAttributes(attrs, R.styleable.CustomView,
        R.attr.customViewStyle, R.style.MyCustomViewStyle);