参考博客:点击打开链接
1.在res/values/下创建一个名为attrs.xml的文件
2.定义属性
带format是在定义属性,不带format是在使用已有的属性。
name的值就是属性的名字,format是限定当前定义的属性能接受什么值。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="mText" format="string" />
<attr name="mTextColor" format="color" />
<attr name="mTextSize" format="dimension" />
<declare-styleable name="MyTextView">
<attr name="mText"/>
<attr name="mTextColor"/>
<attr name="mTextSize"/>
</declare-styleable>
</resources>
系统的属性
<resources>
<declare-styleable name="MyTextView">
<attr name="android:text"/>
</declare-styleable>
</resources>
3.在布局中使用属性
引入命名空间xmlns:openxu="http://schemas.android.com/apk/res-auto"
或者xmlns:openxu="http://schemas.android.com/apk/com.example.openxu.myview"
前者由系统自动查找该属性的来源,后者使用包名。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:openxu="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<view.openxu.com.mytextview.MyTextView
android:layout_width="200dip"
android:layout_height="100dip"
openxu:mTextSize="25sp"
openxu:mText="i love you"
openxu:mTextColor ="#0000ff"
android:background="#ff0000"/>
</LinearLayout>
4.在构造方法中获取自定义属性
public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//获取自定义属性的值
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyTextView, defStyleAttr, 0);
mText = a.getString(R.styleable.MyTextView_mText);
mTextColor = a.getColor(R.styleable.MyTextView_mTextColor, Color.BLACK);
mTextSize = a.getDimension(R.styleable.MyTextView_mTextSize, 100);
a.recycle(); //注意回收
mPaint = new Paint();
mPaint.setTextSize(mTextSize);
mPaint.setColor(mTextColor);
//获得绘制文本的宽和高
mBound = new Rect();
mPaint.getTextBounds(mText, 0, mText.length(), mBound);
}