Android自定義屬性

自定義屬性一般包括如下四步:

1.在values/attrs.xml文件中編寫styleable和attr等標(biāo)簽;
2.自定義一個(gè)繼承自View的CustomView;
3.在自定義的CustomView類中通過(guò)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后面要寫絕對(duì)路徑。-->
<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本來(lái)不帶邊框,通過(guò)自定義給它添加了邊框的屬性,邊框的寬度的屬性。

擴(kuò)展閱讀

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容