Android自定義屬性實現顯示兩行文字的button

最近項目有個需求是實現一個button上顯示兩個按鈕,而且這兩行文字可以改變,最終是通過自定義屬性來解決的,下面是全部過程和代碼:

一、在res/values文件下定義一個attrs.xml文件,format表示參數類型。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    
    <declare-styleable name="test">
        <attr name="tag" format="string" />
        <attr name="num" format="integer" />
    </declare-styleable>

</resources>


二、自定義一個類,繼承Button,獲取到自定義的屬性,並通過onDraw()方法繪製出來:

public class CustomButton extends Button{

    String tag;
    int num;
    
    public CustomButton(Context context) {
        super(context);
    }

    public CustomButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        //獲取自定義的屬性
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.test);
        tag = ta.getString(R.styleable.test_tag);
        num = ta.getInteger(R.styleable.test_num, -1);
        ta.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //繪製第一行文字
        Paint paint = new Paint();
        paint.setTextSize(32);
        float tagWidth = paint.measureText(tag);
        int x = (int) (this.getWidth() - tagWidth)/2;
        int y = this.getHeight()/2;
        canvas.drawText(tag, x, y, paint);
        //繪製第二行文字
        Paint paint1 = new Paint();
        paint1.setTextSize(28);
        paint1.setColor(Color.rgb(0x00,0xff,0x00));
        float numWidth = paint.measureText(num + "");
        int x1 = (int) (this.getWidth() - numWidth)/2;
        int y1 = this.getHeight()/2 + 35;
        canvas.drawText(num+"", x1, y1, paint1);
//        canvas.translate(0,(this.getMeasuredHeight()/2) - (int) this.getTextSize());
    }
}

三、在佈局文件中使用,注意,命名空間xmlns可以簡寫爲:xmlns:appNs="http://schemas.android.com/apk/res-auto"。

<?xml version="1.0" encoding="utf-8"?
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:ljw="http://schemas.android.com/apk/res/com.example.michael.custonview">

    <com.example.michael.custonview.CustomButton
        android:layout_width="0dp"
        android:layout_height="124dp"
        android:layout_weight="1"
        ljw:tag="大"
        ljw:num="12"/>
    <com.example.michael.custonview.CustomButton
        android:layout_width="0dp"
        android:layout_height="124dp"
        android:layout_weight="1"
        ljw:tag="中"
        ljw:num="12"/>
    <com.example.michael.custonview.CustomButton
        android:layout_width="0dp"
        android:layout_height="124dp"
        android:layout_weight="1"
        ljw:tag="小"
        ljw:num="12"/>
    <com.example.michael.custonview.CustomButton
        android:layout_width="0dp"
        android:layout_height="124dp"
        android:layout_weight="1"
        ljw:tag="特小"
        ljw:num="12"/>
</LinearLayout>

最終實現的效果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章