Retrieving Inherited Attributes from a Custom View

I defined a parent styleablefor some custom views as follows

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

Then I defined a child styleablethat inherits the attributes of the parent style, i.e.

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

Now I can get the attribute values ​​from the child style in my user view, but not any attributes of its parent style, i.e. set 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 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();
    }

I am retrieving the attribute correctly state, but the attribute coloralways gives a default value, i.e. white. Am I missing something?

+3
source share
1 answer

attr , getInt .

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

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

All Articles