首先我们自定义几个属性
1 <?xml version="1.0" encoding="utf-8"?> 2 <resources> 3 <declare-styleable name="attrName"> 4 <attr name="name" format="string"></attr> 5 <attr name="number" format="integer"></attr> 6 </declare-styleable> 7 8 9 </resources>
然后布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:customview="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <com.example.administrator.popupmenu.CustomView android:layout_width="100dp" android:layout_height="100dp" android:padding="@dimen/padding" customview:name="@string/hello_world" customview:number="123" /> </LinearLayout>
然后看下自定义view的源码
1 package com.example.administrator.popupmenu; 2 3 import android.content.Context; 4 import android.content.res.TypedArray; 5 import android.util.AttributeSet; 6 import android.util.Log; 7 import android.view.View; 8 9 /** 10 * Created by Administrator on 2015/8/18. 11 */ 12 public class CustomView extends View { 13 14 private static final String TAG = CustomView.class.getSimpleName(); 15 16 public CustomView(Context context, AttributeSet attrs) { 17 super(context, attrs); 18 TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.attrName); 19 String name = ta.getString(R.styleable.attrName_name); 20 int number = ta.getInteger(R.styleable.attrName_number, -1); 21 Log.e(TAG, "name=" + name + " number=" + number); 22 23 /** 24 * attrs在取值的时候 缺陷就是如果值里面还有类似的引用 则取不到正确的值 25 * 需要额外 26 * 27 */ 28 for (int i = 0; i < attrs.getAttributeCount(); i++) { 29 Log.e(TAG, "attrs name=" + attrs.getAttributeName(i) + " attrs value=" + attrs.getAttributeValue(i)); 30 //取出來實際的像素的值 31 if (attrs.getAttributeName(i).equals("padding")) { 32 ; 33 Log.e(TAG, "attrs name=" + attrs.getAttributeName(i) + " attrs value=" + getResources().getDimension(attrs.getAttributeResourceValue(i, -1))); 34 35 } 36 //这个地方就能看出来TypedArray比attrs要好用的多~同时也可以理解两者区别了 37 if (attrs.getAttributeName(i).equals("name")) { 38 ; 39 Log.e(TAG, "attrs name=" + attrs.getAttributeName(i) + " attrs value=" + getResources().getString(attrs.getAttributeResourceValue(i, -1))); 40 41 } 42 } 43 ta.recycle(); 44 45 46 } 47 }
最后看下我们的输出。