自定義View(二)

前面說過了,自定義View主要有下面三種:
1.對現(xiàn)有控件進行擴展
2.通過組合實現(xiàn)新的控件
3.重寫View實現(xiàn)全新控件

對現(xiàn)有控件進行擴展

擴展了一個TextView,有內(nèi)外兩個矩形組成。代碼如下:

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) {
        //在實現(xiàn)原生控件之間,實現(xiàn)我們的邏輯
        //繪制外層矩形
        canvas.drawRect(0,0,getMeasuredWidth(),getMeasuredHeight(),mPaint1);
        //繪制內(nèi)層矩形
        canvas.drawRect(10,10,getMeasuredWidth()-10,getMeasuredHeight()-10,mPaint2);
        //保存畫布狀態(tài)
        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);調(diào)用父類的方法,但是在調(diào)用之前,我們可以實現(xiàn)自己的邏輯。這里這要是畫了兩個矩形,保存畫布,并對畫布進行了平移,平移之后調(diào)用了父類的onDraw()方法。可以看到,即便是我們在布局文件里用到了android:gravity="center"屬性,android:text="擴展的TextView"屬性還是平移了。

通過組合實現(xiàn)新的控件

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


1.定義屬性,在res的Values目錄下創(chuàng)建一個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>
        <!--左邊圖片的自發(fā)定義屬性-->
        <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:百分數(shù), 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; //左側(cè)圖片的背景圖
    //中間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);
        //設(shè)置背景色
        setBackgroundColor(0xFF190D31);
        //獲得atts.xml定義的屬性值,存儲在TypedArray中
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TopBar);
        //左側(cè)圖片
        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的值后,一般要調(diào)用
        // recyle方法來避免重新創(chuàng)建的時候的錯誤
        ta.recycle();

        //創(chuàng)建控件
        img_left=new ImageView(context);
        tv_title=new TextView(context);
        tv_right=new TextView(context);

        // 為創(chuàng)建的組件元素賦值
        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);

        //設(shè)置組件的位置
        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,但是它是還不能響應(yīng)點擊事件的,現(xiàn)在,我們讓自定義的TopBar響應(yīng)點擊事件。修改代碼如下:
在TopBar里加入回調(diào)接口,分別定義了左右控件的點擊回調(diào)時間

 //定義接口,響應(yīng)點擊事件
    public interface topbarClickListener {
        //左按鈕點擊事件
        void leftClick();

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

定義回調(diào)接口,并暴露給調(diào)用者。

 // 映射傳入的接口對象
    private topbarClickListener mListener;

 // 暴露一個方法給調(diào)用者來注冊接口回調(diào)
    public void setOnTopbarClickListener(topbarClickListener mListener) {
        this.mListener = mListener;
    }

對控件設(shè)置回調(diào)事件

 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里實現(xiàn)回調(diào),實現(xiàn)控件的點擊監(jiān)聽。

 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實現(xiàn)全新控件

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



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();  //音頻條的高度,要乘上一個隨機數(shù)
        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; //音頻條的個數(shù)
    private int offset = 5; //音頻條的偏移量
    private double mRandom;  //隨機數(shù)
    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();  //音頻條的高度,要乘上一個隨機數(shù)
        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);
    }
}

代碼下載 https://github.com/baojie0327/ViewAndGroup

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,327評論 6 537
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,996評論 3 423
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,316評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,406評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,128評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,524評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,576評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,759評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,310評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,065評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,249評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,821評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,479評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,909評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,140評論 1 290
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,984評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,228評論 2 375

推薦閱讀更多精彩內(nèi)容