1.attr.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyView"> <attr name="textColor" format="color" /> <attr name="textSize" format="dimension" /> </declare-styleable> </resources>
2.在构造方法中使用
public MyView(Context context,AttributeSet attrs){ super(context,attrs); mPaint = new Paint(); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView); int textColor = a.getColor(R.styleable.MyView_textColor, 0XFFFFFFFF); //怎么获取:名字_ 属性 连接起来就可以 float textSize = a.getDimension(R.styleable.MyView_textSize, 36); mPaint.setTextSize(textSize); mPaint.setColor(textColor); a.recycle(); }
3.在布局文件中使用
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:test="http://schemas.android.com/apk/res/com.android.tutor" //自定义属性前缀 与 包名 android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <com.android.tutor.MyView android:layout_width="fill_parent" android:layout_height="fill_parent" test:textSize="20px" test:textColor="#fff"/> </LinearLayout>
Android自定义属性:attr.xml 与 TypedArray,布布扣,bubuko.com
Android自定义属性:attr.xml 与 TypedArray
原文:http://www.cnblogs.com/yuyutianxia/p/3716618.html