上一节已经说了自定义属性的用法,实现步骤有如下几步:


  1. 自定义一个CustomView(extends View )类
  2. 编写values/attrs.xml,在其中编写declare-styleable和attr等标签元素
  3. 在布局文件中CustomView使用自定义的属性(注意添加自己的namespace)
  4. 在CustomView的构造方法中通过TypedArray获取自定义属性



知道了这些,我们完全可以写自己的view了,但为什么要这样呢?它是如何运行的呢?正所谓知其然,更要知其所以然,看了鸿洋大神的文章,真是有种醍醐灌顶的感觉啊


好了,不拍马屁了,切入正题




首先,写一个自定义属性文件


<resources>
 
 

 
 
    <!-- declare-styleable的 name是可以随便取名字的 -->
 
 
    <declare-styleable name="CustomAttrView">
 
 
        <attr name="text" format="string" />
 
 
    </declare-styleable>
 
 

 
 
</resources>


编写自定义view


public class CustomAttrView extends View {
 
 

 
 
    String TAG = "tag";
 
 
    Paint paint;
 
 
    String text;
 
 

 
 
    public CustomAttrView(Context context) {
 
 
        this(context, null);
 
 
    }
 
 

 
 
    public CustomAttrView(Context context, AttributeSet attrs) {
 
 
        super(context, attrs);
 
 
        paint = new Paint();
 
 
        TypedArray typedArray = context.obtainStyledAttributes(attrs,
 
 
                R.styleable.CustomAttrView);
 
 

 
 
        text = typedArray.getString(R.styleable.CustomAttrView_text);
 
 
        Log.i(TAG, "--text = " + text);
 
 
        typedArray.recycle();
 
 
    }
 
 

 
 
    @Override
 
 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
 
 
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
 
 
    }
 
 

 
 
    @Override
 
 
    protected void onDraw(Canvas canvas) {
 
 
        paint.setTextSize(80);
 
 
        canvas.drawText(text, 80f, 80f, paint);
 
 
    }
 
 
}




在activity_main.xml文件中引用


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 
 
    xmlns:tools="http://schemas.android.com/tools"
 
 
    xmlns:custom="http://schemas.android.com/apk/res/com.example.activity"
 
 
    android:layout_width="match_parent"
 
 
    android:layout_height="match_parent" >
 
 

 
 
    <com.example.activity.view.CustomAttrView
 
 
        android:layout_width="200dp"
 
 
        android:layout_height="100dp"
 
 
        custom:text="520" />
 
 

 
 
</RelativeLayout>


运行后输出的log日志为:


自定义属性剖析_android开发



继续看代码,构造函数里有一个AttributeSet (参数集),具体的用途是什么?
修改下CustomAttrView



public CustomAttrView(Context context, AttributeSet attrs) {
  
        super(context, attrs);
  
        paint = new Paint();
  
        TypedArray typedArray = context.obtainStyledAttributes(attrs,
  
                R.styleable.CustomAttrView);
  

  
        text = typedArray.getString(R.styleable.CustomAttrView_text);
  
        Log.i(TAG, "--text = " + text);
  

  
        typedArray.recycle();
  

  
        int count = attrs.getAttributeCount();
  
        for (int i = 0; i < count; i++) {
  
            String attrName = attrs.getAttributeName(i);
  
            String attrVal = attrs.getAttributeValue(i);
  
            Log.i(TAG, "--attrName = " + attrName + " , attrVal = " + attrVal);
  
        }
  
    }

看下log输出


自定义属性剖析_自定义_02


可以看出,AttributeSet保存的是该View声明的所有的属性,通过AttributeSet可以获得布局文件中定义的所有属性的key和value(还有一些方法,根据提示可以用下)


对比两次log,好像TypedArray并没有什么用,想要获得我自定义的text属性直接用AttributeSet也可以,好,修改下activity_main.xml



<com.example.activity.view.CustomAttrView
  
        android:layout_width="@dimen/dp200"
  
        android:layout_height="@dimen/dp100"
  
        custom:text="@string/hello_world" />


再次运行,看下log


自定义属性剖析_自定义_03


通过AttributeSet获取的值,如果是引用都变成了@+数字的字符串。而使用TypedArray获取的值没有变化。TypedArray的作用现在明白了——TypedArray其实是用来简化我们的工作的,比如上例,如果布局中的属性的值是引用类型(比如:@dimen/dp100),如果使用AttributeSet去获得最终的像素值,那么需要先拿到id,然后再去解析id。而TypedArray正是帮我们简化了这个过程

捎带一下通过AttributeSet获取最终的像素值的过程:

int widthDimensionId =  attrs.getAttributeResourceValue(0, -1);
        Log.e(TAG, "layout_width= "+getResources().getDimension(widthDimensionId));



我的自定义属性文件只写了一个custom:text,很多情况下自定义属性的含义在android系统中已经有了明确的定义,比如我这个,那么直接使用android:text是否可以?

修改下attrs.xml


<declare-styleable name="CustomAttrView">
  
        <attr name="android:text" />
  
    </declare-styleable>



因为我们使用的是已经定义好的属性,所以不需要去添加format属性(声明和使用的区别就是有没有format)。 
然后在类中这么获取:typedArray.getString(R.styleable.CustomAttrView_android_text);

布局文件中直接android:text="@string/hello_world"即可。

系统中定义的属性,其实和我们自定义属性的方式类似,你可以在sdk/platforms/android-xx/data/res/values该目录下看到系统中定义的属性。然后你可以在系统提供的View(eg:TextView)的构造方法中发现TypedArray获取属性的代码(自己去看一下)。

既然declare-styleable这个标签的name都能随便写,那么考虑问题:

styleable 的含义是什么?可以不写嘛?我自定义属性,我声明属性就好了,为什么一定要写个styleable呢?

其实的确是可以不写的,怎么做呢?


首先删除declare-styleable的标签



atrrs.xml变为

<?xml version="1.0" encoding="utf-8"?><resources><attr name="text" format="string" /></resources>

CustomAttrView.java如下


public class CustomAttrView extends View {
  
  

  
  
    String TAG = "tag";
  
  
    Paint paint;
  
  
    String text;
  
  
    private static final int[] mAttr = { R.attr.text };
  
  
    private static final int ATTR_ANDROID_TEXT = 0;
  
  

  
  
    public CustomAttrView(Context context) {
  
  
        this(context, null);
  
  
    }
  
  

  
  
    public CustomAttrView(Context context, AttributeSet attrs) {
  
  
        super(context, attrs);
  
  
        paint = new Paint();
  
  
        TypedArray typedArray = context.obtainStyledAttributes(attrs, mAttr);
  
  

  
  
        text = typedArray.getString(ATTR_ANDROID_TEXT);
  
  
        Log.i(TAG, "--text = " + text);
  
  

  
  
        typedArray.recycle();
  
  

  
  
    }
  
  

  
  
}

对比下两个构造函数,可以看到我们声明了一个int数组,数组中的元素就是我们想要获取的attr的id。并且我们根据元素的在数组中的位置,定义了一些整形的常量代表其下标,然后通过TypedArray进行获取。


还有如下区别:


R.styleable.CustomAttrView ——> mAttr
R.styleable.CustomAttrView_text——> ATTR_ANDROID_TEXT(0)
其实android在其内部也会这么做,按照传统的写法,它会在R.java生成如下代码:


public static final class attr {
  
  
      
  
  
        public static final int text = 0x7f010000;
  
  
    }
  
public static final class styleable {
  
  
 public static final int[] CustomAttrView = {
   
   
            0x7f010000
   
   
        };
  
  
    public static final int CustomAttrView_text = 0;
   
   
    };
  
  
}


styleale的的作用就是使系统可以完成很多常量(int[]数组,下标常量等)的编写,简化我们的开发工作。那么大家肯定还知道declare-styleable的name属性,一般情况下写的都是我们自定义View的类名。主要为了直观的表达,该declare-styleable的属性,都是改View所用的。

套用下鸿洋大神的总结:

  • attrs.xml里面的declare-styleable以及item,android会根据其在R.java中生成一些常量方便我们使用(aapt干的),本质上,我们可以不声明declare-styleable仅仅声明所需的属性即可。
  • 我们在View的构造方法中,可以通过AttributeSet去获得自定义属性的值,但是比较麻烦,而TypedArray可以很方便的去获取。
  • 我们在自定义View的时候,可以使用系统已经定义的属性。


源代码