1. 程式人生 > >自定義View(二)

自定義View(二)

前面說過了,自定義View主要有下面三種:
1.對現有控制元件進行擴充套件
2.通過組合實現新的控制元件
3.重寫View實現全新控制元件

對現有控制元件進行擴充套件

擴充套件了一個TextView,有內外兩個矩形組成。程式碼如下:

public class MyTextView extends TextView{

    private Paint mPaint1,mPaint2;

    public MyTextView(Context context) {
        super(context);
        init();
    }

    public
MyTextView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } /** * 初始化 */ private void init(){ mPaint1=new
Paint(); mPaint1.setColor(Color.RED); mPaint1.setStyle(Paint.Style.FILL); mPaint2=new Paint(); mPaint2.setColor(Color.YELLOW); mPaint2.setStyle(Paint.Style.FILL); } @Override protected void onDraw(Canvas canvas) { //在實現原生控制元件之間,實現我們的邏輯 //繪製外層矩形
canvas.drawRect(0,0,getMeasuredWidth(),getMeasuredHeight(),mPaint1); //繪製內層矩形 canvas.drawRect(10,10,getMeasuredWidth()-10,getMeasuredHeight()-10,mPaint2); //儲存畫布狀態 canvas.save(); // 繪製文字前各平移100畫素 canvas.translate(100, 100); //父類完成的方法,繪製文字 super.onDraw(canvas); canvas.restore(); } }
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <com.example.ahuang.viewandgroup.View.MyTextView
            android:layout_width="200dp"
            android:layout_height="100dp"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="20dp"
            android:gravity="center"
            android:text="擴充套件的TextView"/>
    </LinearLayout>


在onDraw()方法裡,有個 super.onDraw(canvas);呼叫父類的方法,但是在呼叫之前,我們可以實現自己的邏輯。這裡這要是畫了兩個矩形,儲存畫布,並對畫布進行了平移,平移之後呼叫了父類的onDraw()方法。可以看到,即便是我們在佈局檔案裡用到了android:gravity=”center”屬性,android:text=”擴充套件的TextView”屬性還是平移了。

通過組合實現新的控制元件

建立組合控制元件,通常需要繼承一個合適的ViewGroup,我們一般要給它指定一些可配置的屬性,讓它變得更具擴充套件性。例如,很多app都有跟下圖類似的TopBar控制元件,我們完全可以自己定義一個類似的TopBar控制元件。


1.定義屬性,在res的Values目錄下建立一個attrs.xml的屬性定義檔案。主要是為TopBar提供可自定義的屬性。

<resources>
    <declare-styleable name="TopBar">
        <!--中間title的自定義屬性-->
        <attr name="mTitle" format="string"></attr>
        <attr name="mTitleSize" format="dimension"></attr>
        <attr name="mTitleColor" format="color"></attr>
        <!--左邊圖片的自發定義屬性-->
        <attr name="mLeftBackGround" format="reference"></attr>
        <!--右邊TextView的自定義屬性-->
        <attr name="rightTitle" format="string"></attr>
        <attr name="rightTitleSize" format="dimension"></attr>
        <attr name="rightTextColor" format="color"></attr>
    </declare-styleable>
</resources>

我們定義了控制元件名字,字型顏色,背景3個屬性,format是值該屬性的取值型別:
一共有:string,color,demension,integer,enum,reference,float,boolean,fraction,flag;
reference:參考某一資源ID,color:顏色值,boolean:布林值,dimension:尺寸值,float:浮點值
integer:整型值,string:字串,fraction:百分數, enum:列舉值, flag:位或運算

2.自定義TopBar,獲取自定義的屬性。

public class TopBar extends RelativeLayout {
    //控制元件
    private ImageView img_left;
    private TextView tv_title;
    private TextView tv_right;
    // 佈局屬性,用來控制組件元素在ViewGroup中的位置
    private LayoutParams mLeftParams, mTitlepParams, mRightParams;

    // 左控制元件的屬性值,即我們在atts.xml檔案中定義的屬性
    private Drawable mBackGround; //左側圖片的背景圖
    //中間title的屬性值
    private float mTitleTextSize;
    private int mTitleTextColor;
    private String mTitle;
    //右邊TextView的屬性值
    private int mRightTextColor;
    private float mRightTextSize;
    private String mRightText;


    public TopBar(Context context) {
        this(context, null);
    }

    public TopBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TopBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //設定背景色
        setBackgroundColor(0xFF190D31);
        //獲得atts.xml定義的屬性值,儲存在TypedArray中
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TopBar);
        //左側圖片
        mBackGround = ta.getDrawable(R.styleable.TopBar_mLeftBackGround);
        //中間title
        mTitleTextSize = ta.getDimension(R.styleable.TopBar_mTitleSize, 10);
        mTitleTextColor = ta.getColor(R.styleable.TopBar_mTitleColor, 0);
        mTitle = ta.getString(R.styleable.TopBar_mTitle);
        //右邊Title
        mRightTextColor = ta.getColor(R.styleable.TopBar_rightTextColor, 0);
        mRightTextSize = ta.getDimension(R.styleable.TopBar_rightTitleSize, 1);
        mRightText = ta.getString(R.styleable.TopBar_rightTitle);
        // 獲取完TypedArray的值後,一般要呼叫
        // recyle方法來避免重新建立的時候的錯誤
        ta.recycle();

        //建立控制元件
        img_left=new ImageView(context);
        tv_title=new TextView(context);
        tv_right=new TextView(context);

        // 為建立的元件元素賦值
        img_left.setBackground(mBackGround);

        tv_title.setText(mTitle);
        tv_title.setTextColor(mTitleTextColor);
        tv_title.setTextSize(mTitleTextSize);

        tv_right.setText(mRightText);
        tv_right.setTextColor(mRightTextColor);
        tv_right.setTextSize(mRightTextSize);

        //設定元件的位置
        mLeftParams=new LayoutParams(60, 60);
        mLeftParams.addRule(ALIGN_PARENT_LEFT,TRUE);
        mLeftParams.addRule(CENTER_VERTICAL,TRUE);
        addView(img_left,mLeftParams);
        mTitlepParams=new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mTitlepParams.addRule(CENTER_IN_PARENT,TRUE);
        addView(tv_title,mTitlepParams);
        mRightParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mRightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);
        mRightParams.addRule(RelativeLayout.CENTER_VERTICAL, TRUE);
        addView(tv_right, mRightParams);
    }

3.在佈局檔案裡引用我們自定義的TopBar
需要注意的是,在Android Studio中,第三方控制元件都使用如下程式碼來引入名字空間
xmlns:custom=”http://schemas.android.com/apk/res-auto” 將引入的第三方控制元件的名字空間取為custom,之後在xml檔案中使用自定義的屬性時,就可以通過這個名字空間來引用。

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <com.example.ahuang.viewandgroup.View.TopBar
            android:layout_width="match_parent"
            android:layout_height="45dp"
            custom:mLeftBackGround="@mipmap/back_icon"
            custom:mTitle="購物車"
            custom:mTitleColor="@android:color/white"
            custom:mTitleSize="5sp"
            custom:rightTextColor="@android:color/white"
            custom:rightTitle="編輯"
            custom:rightTitleSize="5sp"/>
    </LinearLayout>


4.雖然我們定義了需要的TopBar,但是它是還不能響應點選事件的,現在,我們讓自定義的TopBar響應點選事件。修改程式碼如下:
在TopBar里加入回撥介面,分別定義了左右控制元件的點選回撥時間

 //定義介面,響應點選事件
    public interface topbarClickListener {
        //左按鈕點選事件
        void leftClick();

        //右按鈕點選事件
        void rightClick();
    }

定義回撥介面,並暴露給呼叫者。

 // 對映傳入的介面物件
    private topbarClickListener mListener;

 // 暴露一個方法給呼叫者來註冊介面回撥
    public void setOnTopbarClickListener(topbarClickListener mListener) {
        this.mListener = mListener;
    }

對控制元件設定回撥事件

 img_left.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.leftClick();
            }
        });

        tv_right.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.rightClick();
            }
        });

在Activity裡實現回撥,實現控制元件的點選監聽。

 mTopBar.setOnTopbarClickListener(new TopBar.topbarClickListener() {
            @Override
            public void leftClick() {
                Toast.makeText(CustomViewActivity.this, "click left", Toast.LENGTH_SHORT)
                        .show();
            }

            @Override
            public void rightClick() {
                Toast.makeText(CustomViewActivity.this, "click right", Toast.LENGTH_SHORT)
                        .show();
            }
        });


最後,要說明一點的是,TopBar一般在很多頁面頂部引用,為了方便,我們可以放在一個頭佈局裡面,然後再用到的地方通過include引用。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:custom="http://schemas.android.com/apk/res-auto"
              android:layout_width="match_parent"
              android:layout_height="45dp">
    <com.example.ahuang.viewandgroup.View.TopBar
        android:id="@+id/topBar"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        custom:mLeftBackGround="@mipmap/back_icon"
        custom:mTitle="購物車"
        custom:mTitleColor="@android:color/white"
        custom:mTitleSize="5sp"
        custom:rightTextColor="@android:color/white"
        custom:rightTitle="編輯"
        custom:rightTitleSize="5sp"/>

</LinearLayout>

在用到的地方,通過

<include layout="@layout/head_layout"></include> 新增控制元件。

重寫View實現全新控制元件

如下圖所示的圖片,在很多音樂播放器上會有,但是android裡沒有現成的控制元件,所以可以自定義一個類似的控制元件。相信大家可以很快找到思路,也就是繪製一個個矩形,每個矩形之間稍微偏移一點距離即可。

1.初始化操作

 private void init() {
        mPaint = new Paint();
        mPaint.setColor(Color.GREEN);
        mPaint.setStyle(Paint.Style.FILL);
        mRectCount = 12;
    }

2.主繪製方法

@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (int i = 0; i < mRectCount; i++) {
            mRandom = Math.random();
            canvas.drawRect(mRectWidth * i + offset, (float) (mRectHeight * mRandom), mRectWidth * (i+1),
                   mRectHeight, mPaint);
        }
        postInvalidateDelayed(300);
    }

3.為了達到一個更好的效果,增加一個LinearGradient漸變效果

 @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = getWidth();
        mRectWidth = mWidth / mRectCount; //音訊條的寬度
        mRectHeight = getHeight();  //音訊條的高度,要乘上一個隨機數
        mLinearGradient=new LinearGradient(0,0,mRectWidth,mRectHeight,
                Color.BLUE,Color.GREEN, Shader.TileMode.CLAMP);
        mPaint.setShader(mLinearGradient);
    }

所有程式碼如下:

public class AudioBar extends View {

    private Paint mPaint;  //定義畫筆
    private int mWidth; //螢幕的寬度
    private int mRectWidth;  //音訊條的寬度
    private int mRectHeight;  //音訊條的高度
    private int mRectCount; //音訊條的個數
    private int offset = 5; //音訊條的偏移量
    private double mRandom;  //隨機數
    private LinearGradient mLinearGradient;


    public AudioBar(Context context) {
        this(context, null);
    }

    public AudioBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AudioBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setColor(Color.GREEN);
        mPaint.setStyle(Paint.Style.FILL);
        mRectCount = 12;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = getWidth();
        mRectWidth = mWidth / mRectCount; //音訊條的寬度
        mRectHeight = getHeight();  //音訊條的高度,要乘上一個隨機數
        mLinearGradient=new LinearGradient(0,0,mRectWidth,mRectHeight,
                Color.BLUE,Color.GREEN, Shader.TileMode.CLAMP);
        mPaint.setShader(mLinearGradient);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (int i = 0; i < mRectCount; i++) {
            mRandom = Math.random();
            canvas.drawRect(mRectWidth * i + offset, (float) (mRectHeight * mRandom), mRectWidth * (i+1),
                   mRectHeight, mPaint);
        }
        postInvalidateDelayed(300);
    }
}