自定義View(二)

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

對(duì)現(xiàn)有控件進(jìn)行擴(kuò)展

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

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) {
        //在實(shí)現(xiàn)原生控件之間,實(shí)現(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="擴(kuò)展的TextView"/>
    </LinearLayout>

在onDraw()方法里,有個(gè) super.onDraw(canvas);調(diào)用父類的方法高镐,但是在調(diào)用之前,我們可以實(shí)現(xiàn)自己的邏輯畸冲。這里這要是畫了兩個(gè)矩形嫉髓,保存畫布,并對(duì)畫布進(jìn)行了平移邑闲,平移之后調(diào)用了父類的onDraw()方法算行。可以看到苫耸,即便是我們?cè)诓季治募镉玫搅薬ndroid:gravity="center"屬性州邢,android:text="擴(kuò)展的TextView"屬性還是平移了。

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

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


1.定義屬性,在res的Values目錄下創(chuàng)建一個(gè)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個(gè)屬性,format是值該屬性的取值類型:
一共有:string,color,demension,integer,enum,reference,float,boolean,fraction,flag;
reference:參考某一資源ID倘核,color:顏色值泣侮,boolean:布爾值,dimension:尺寸值紧唱,float:浮點(diǎn)值
integer:整型值活尊,string:字符串,fraction:百分?jǐn)?shù)漏益, enum:枚舉值蛹锰, flag:位或運(yùn)算

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;

    // 左控件的屬性值,即我們?cè)赼tts.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定義的屬性值轻庆,存儲(chǔ)在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)建的時(shí)候的錯(cuò)誤
        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文件中使用自定義的屬性時(shí),就可以通過這個(gè)名字空間來引用蛾方。

<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)點(diǎn)擊事件的,現(xiàn)在桩砰,我們讓自定義的TopBar響應(yīng)點(diǎn)擊事件拓春。修改代碼如下:
在TopBar里加入回調(diào)接口,分別定義了左右控件的點(diǎn)擊回調(diào)時(shí)間

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

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

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

 // 映射傳入的接口對(duì)象
    private topbarClickListener mListener;

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

對(duì)控件設(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里實(shí)現(xiàn)回調(diào)枢步,實(shí)現(xiàn)控件的點(diǎ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();
            }
        });

最后,要說明一點(diǎn)的是醉途,TopBar一般在很多頁面頂部引用矾瑰,為了方便,我們可以放在一個(gè)頭布局里面隘擎,然后再用到的地方通過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實(shí)現(xiàn)全新控件

如下圖所示的圖片采幌,在很多音樂播放器上會(huì)有劲够,但是android里沒有現(xiàn)成的控件,所以可以自定義一個(gè)類似的控件休傍。相信大家可以很快找到思路征绎,也就是繪制一個(gè)個(gè)矩形,每個(gè)矩形之間稍微偏移一點(diǎ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.為了達(dá)到一個(gè)更好的效果程拭,增加一個(gè)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();  //音頻條的高度叉弦,要乘上一個(gè)隨機(jī)數(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; //音頻條的個(gè)數(shù)
    private int offset = 5; //音頻條的偏移量
    private double mRandom;  //隨機(jī)數(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();  //音頻條的高度最爬,要乘上一個(gè)隨機(jī)數(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)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末牲距,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子逢净,更是在濱河造成了極大的恐慌哥放,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,657評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件爹土,死亡現(xiàn)場離奇詭異婶芭,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)着饥,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門犀农,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人宰掉,你說我怎么就攤上這事呵哨。” “怎么了轨奄?”我有些...
    開封第一講書人閱讀 164,057評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵孟害,是天一觀的道長。 經(jīng)常有香客問我挪拟,道長挨务,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,509評(píng)論 1 293
  • 正文 為了忘掉前任玉组,我火速辦了婚禮谎柄,結(jié)果婚禮上惯雳,老公的妹妹穿的比我還像新娘朝巫。我一直安慰自己,他們只是感情好石景,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著筷黔,像睡著了一般必逆。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上凰棉,一...
    開封第一講書人閱讀 51,443評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音掏秩,去河邊找鬼映凳。 笑死诈豌,一個(gè)胖子當(dāng)著我的面吹牛矫渔,可吹牛的內(nèi)容都是我干的庙洼。 我是一名探鬼主播油够,決...
    沈念sama閱讀 40,251評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼碌补!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起袜啃,我...
    開封第一講書人閱讀 39,129評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎雪猪,沒想到半個(gè)月后抬虽,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體休涤,經(jīng)...
    沈念sama閱讀 45,561評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評(píng)論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了弯菊。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片纵势。...
    茶點(diǎn)故事閱讀 39,902評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖管钳,靈堂內(nèi)的尸體忽然破棺而出钦铁,到底是詐尸還是另有隱情,我是刑警寧澤才漆,帶...
    沈念sama閱讀 35,621評(píng)論 5 345
  • 正文 年R本政府宣布牛曹,位于F島的核電站,受9級(jí)特大地震影響醇滥,放射性物質(zhì)發(fā)生泄漏黎比。R本人自食惡果不足惜超营,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望阅虫。 院中可真熱鬧演闭,春花似錦、人聲如沸颓帝。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽购城。三九已至吕座,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間瘪板,已是汗流浹背吴趴。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評(píng)論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留篷帅,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,025評(píng)論 2 370
  • 正文 我出身青樓拴泌,卻偏偏與公主長得像魏身,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子蚪腐,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評(píng)論 2 354

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