自定義屬性一般包括如下四步:
1.在values/attrs.xml文件中編寫styleable和attr等標(biāo)簽辩蛋;
2.自定義一個(gè)繼承自View的CustomView;
3.在自定義的CustomView類中通過TypedArray獲得屬性,并進(jìn)行相應(yīng)的操作浪汪;
4.在布局文件中使用自定義的CustomView惰拱。
代碼示例
values/attrs.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="test">
<attr name="boundWidth" format="dimension"/>
<attr name="bound" format="color"/>
</declare-styleable>
</resources>
自定義的CustomView類
public class CustomView extends TextView {
protected float boundWidth;
protected int boundColor;
private Paint mPaint;
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.test);
boundWidth = ta.getDimension(R.styleable.test_boundWidth,1.0f);
boundColor = ta.getColor(R.styleable.test_bound, Color.BLACK);
mPaint = new Paint();
mPaint.setColor(boundColor);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(boundWidth);
ta.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawRect(0,0,getWidth(),getHeight(),mPaint);
super.onDraw(canvas);
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<!-- 1.custom名字隨意取雌贱。
2.如果是以lib的形式res后面要寫絕對路徑。-->
<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-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.customattr.CustomView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:padding="8dp"
android:text="hello"
custom:boundWidth="8dp"
custom:bound="#e14949"/>
</RelativeLayout>
可以看到這是一個(gè)繼承自TextView的CustomView,TextView本來不帶邊框偿短,通過自定義給它添加了邊框的屬性欣孤,邊框的寬度的屬性。
擴(kuò)展閱讀
- [Android] View 的三種自定義方式:擴(kuò)展昔逗,組合降传,重寫;
- [android 為TextView添加邊框](android 為TextView添加邊框);
- Android 深入理解Android中的自定義屬性;
- Android中自定義樣式與View的構(gòu)造函數(shù)中的第三個(gè)參數(shù)defStyle的意義;
- Android中自定義屬性(attrs.xml勾怒,TypedArray的使用)婆排。