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

时间:2016-02-04 15:02:38

标签: android attributes styling

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

我们走了:我有一个自定义视图,我们称之为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”键,如果可能,如何从中获取信息?

Bonus:我已经能够通过这样做来创建这个“customViewStyle”键:

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

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

1 个答案:

答案 0 :(得分:2)

  

我如何定义这个&#34; customViewStyle&#34;键?

任何<attr name="customViewStyle" format="reference"/>标签的

<declare-styleable>

  

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

制作具有所需属性的样式。您已经在帖子中使用MyCustomViewStyle条目完成了此操作,但您已经为其提供了不存在的父级样式(据我所知)。我可能会使用`parent =&#34; android:Widget&#34;除非别的东西更合适。

我假设你的自定义视图类已经使用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);