从自定义视图中检索继承的属性 [英] Retrieving Inherited Attributes from Custom View

查看:29
本文介绍了从自定义视图中检索继承的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为一些自定义视图定义了一个父 styleable 如下

I've defined a parent styleable for some custom views as follows

<declare-styleable name="ParentView">
    <attr name="color" format="color" />
    <attr name="rotate" format="float" />
</declare-styleable>

然后我定义了一个子 styleable,它继承了父 styleable 的属性,即,

I've then defined a child styleable that inherits the attributes from the parent styleable, i.e.,

<declare-styleable name="ParentView.ChildView">
    <attr name="state">
        <enum name="state0" value="0"/>
        <enum name="state1" value="1"/>
    </attr>
</declare-styleable>

现在,我可以在我的自定义视图中从子样式中检索属性值,但不能从其父样式中检索任何属性,即将我在 xml 中的自定义视图设置为

Now, I can retrieve the attribute values from the child styleable in my custom view, but not any attributes from its parent styleable, i.e., setting my custom view in xml as

<com.example.android.MyCustomView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    custom:color="@color/orange"
    custom:state="state1" />

并在我的自定义视图的构造函数中使用以下代码

and using the following code in my custom view's constructor

TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ParentView_ChildView, 0, 0);
    try {
        state = array.getInt(R.styleable.ParentView_ChildView_state, state);
        color = array.getInt(R.styleable.ParentView_color, Color.WHITE);
    }
    finally {
        array.recycle();
    }

我正确检索了 state 属性,但 color 属性总是只给出其默认值,即白色.我在这里错过了什么吗?

I retrieve the state attribute correctly, but the color attribute always just gives its default value, i.e. white. Am I missing something here?

推荐答案

您已在 attr 文件中将颜色定义为一种颜色格式,但您在代码中执行了 getInt.

You have defined color as a format of color in your attr file, yet you are doing getInt in your code.

尝试更改此行

color = array.getInt(R.styleable.ParentView_color, Color.WHITE);

color = array.getColor(R.styleable.ParentView_color, Color.WHITE);

这篇关于从自定义视图中检索继承的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆