【问题标题】:Background color from the TypedArrayTypedArray 的背景颜色
【发布时间】:2018-12-21 03:50:06
【问题描述】:

我在 Android 中有一个自定义视图,并希望加载由 attrs 和 TypedArray 在自定义视图上设置的所有属性。例如,我在 xml 布局中定义了一个背景色属性,但无法在构造函数中加载它。

我尝试了但没有成功。

// To be done, get the background color from the attributes.
TypedArray l_typedArray = this.getContext().obtainStyledAttributes(attrs,??                                , 0);
// not working Color backColor = l_typedArray.getColor()

【问题讨论】:

  • 您能否更具体地了解“不工作”?是抛出异常、返回null等吗?
  • 我找到了我的问题的答案。

标签: android typedarray


【解决方案1】:

您可以在此处读取的属性位于 values\attrs.xml 中的 attrs.xml - 可以如下所示

<resources>
<declare-styleable name="bubbleview">
    <!-- Color of the playground  -->
    <attr name="playgroundcolor" format="reference|color" />
    <!-- Color of the canon arrow coming out of the top ball  -->
    <attr name="canoncolor" format="reference|color" />
    <!-- Color of the score text  -->
    <attr name="scorecolor" format="reference|color"/>
</declare-styleable>
</resources>





enter code here
{
TypedArray l_typedArray = 
getContext().obtainStyledAttributes(attrs,R.styleable.bubbleview);
m_scorecolor = l_typedArray.getColor(R.styleable.bubbleview_scorecolor,Color.RED);
m_canoncolor = l_typedArray.getColor(R.styleable.bubbleview_canoncolor,Color.BLUE);
l_typedArray.recycle(); // never forget this one!!!
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 2019-08-30
    • 1970-01-01
    相关资源
    最近更新 更多