【问题标题】:Android : Create your own attribute names in styles.xmlAndroid : 在 styles.xml 中创建自己的属性名称
【发布时间】:2016-02-04 15:02:37
【问题描述】:

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

我们开始吧:我有一个自定义视图,我们称之为 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"/>

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

【问题讨论】:

    标签: android attributes styling


    【解决方案1】:

    如何定义这个“customViewStyle”键?

    &lt;attr name="customViewStyle" format="reference"/&gt;在任何&lt;declare-styleable&gt; 标签之外

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

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

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

    【讨论】:

    • "你给了它一个不存在的父样式" 是的,我知道,我只是想展示我希望我的代码看起来像什么,但你接下来说的只是做了我想要的帽子。你先生应该得到一块饼干!谢谢兄弟,我可以回去工作了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多