android – 如何从AttributeSet中可靠地获取颜色?

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

解决方法

假设您已经定义了自定义颜色属性,如下所示:
<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();
   }
}

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

<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方法在任何情况下都将返回颜色值.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...