【问题标题】:How can I reliably get a color from an AttributeSet?如何可靠地从 AttributeSet 中获取颜色?
【发布时间】:2012-11-22 12:33:59
【问题描述】:

我想创建一个自定义类,当在 Android XML 文件中布局时,该类将颜色作为其属性之一。但是,颜色可以是一种资源,也可以是许多直接颜色规范之一(例如十六进制值)。是否有一种简单的首选方法可以使用AttributeSet 检索颜色,因为表示颜色的整数可以引用资源值或 ARGB 值?

【问题讨论】:

    标签: android xml parsing colors


    【解决方案1】:

    假设您已经像这样定义了自定义颜色属性:

    <declare-styleable name="color_view">
        <attr name="my_color" format="color" />
    </declare-styleable>
    

    然后在视图的构造函数中,您可以像这样检索颜色:

    public ColorView(Context context, AttributeSet attrs) {
       super(context, attrs);
    
       TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.color_view);
       try {
           int color = a.getColor(R.styleable.color_view_my_color, 0);
           setBackgroundColor(color);
       } finally {
           a.recycle();
       }
    }
    

    您实际上不必担心 color 属性是如何填充的,就像这样

    <com.test.ColorView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:my_color="#F00"
        />
    

    或者像这样:

    <com.test.ColorView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:my_color="@color/red"
        />
    

    getColor 方法在任何情况下都会返回一个颜色值。

    【讨论】:

    • 别忘了回收你的TypedArray
    猜你喜欢
    • 2018-03-07
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2017-08-05
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多