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

3
我需要一些帮助,我已经浏览了一段时间,但是我找到的主题都无法解决我的问题。希望你能帮助我!
以下是问题描述:我有一个自定义视图,让我们称其为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"/>

但我还没有找到如何利用它。
1个回答

2

如何定义“customViewStyle”键?

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

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

创建一个具有所需属性的样式。您已经在帖子中使用了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);

"你给它一个不存在的父样式" 是的,我知道,我只是想展示一下我想让我的代码看起来像什么,但是你接下来说的话正好做到了我想要的。你值得拥有一块饼干! 谢谢兄弟,现在我可以回去工作了! - TCleard

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