【问题标题】:Retrieving Inherited Attributes from Custom View从自定义视图中检索继承的属性
【发布时间】:2014-02-20 15:36:18
【问题描述】:

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

<declare-styleable name="ParentView">
    <attr name="color" format="color" />
    <attr name="rotate" format="float" />
</declare-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 属性始终只给出其默认值,即白色。我在这里错过了什么吗?

【问题讨论】:

    标签: android android-custom-view


    【解决方案1】:

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

    尝试更改此行

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      • 2011-11-13
      • 2011-01-22
      相关资源
      最近更新 更多