从自定义视图中检索继承属性

4

我定义了一个父styleable,适用于一些自定义视图,如下所示:

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

然后我定义了一个子styleable,该子styleable继承了来自父styleable的属性,即:

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

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

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

在我的自定义视图的构造函数中使用以下代码:
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属性总是只给出其默认值,即白色。这里我漏掉了什么吗?

1个回答

0

你在属性文件中将颜色定义为颜色格式,但是在代码中却使用了 getInt 方法。

尝试更改这一行:

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

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

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