国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

了解自定義View和繼承View,繼承ViewGroup,繼承已有View,繼承已有ViewGroup實(shí)例ji

2019-11-09 18:54:49
字體:
供稿:網(wǎng)友

自定義View的分類

繼承View

當(dāng)我們需要實(shí)現(xiàn)的效果是一個不規(guī)則效果的時候,那么這時就需要繼承 View 來實(shí)現(xiàn)了,我們需要重寫 onDraw 方法,在該方法里實(shí)現(xiàn)各種不規(guī)則的圖形和效果。當(dāng)我們使用這種方式的時候,需要自己去處理 warp_content 和 padding。

繼承ViewGroup

當(dāng)系統(tǒng)所提供的 LinearLayout、FrameLayout 等布局控件無法滿足我們的需求時,這時我們就需要使用這種方式來實(shí)現(xiàn)自己想要的布局效果了。當(dāng)我們使用這種方式的時候,需要重寫 onLayout 方法來對子 View 進(jìn)行布局,以及測量本身和子 View 寬高,還需要處理本身的 padding 和子 View 的 margin。

繼承已有View

當(dāng)我們需要基于已有的 View 進(jìn)行擴(kuò)展或修改的時候,那么就可以使用這種方式。比如說,我們需要一個圓角的 ImageView,那么這時就可以繼承 ImageView 進(jìn)行修改了。當(dāng)我們使用這種方式的時候,一般不需要自己去處理 wrap_content 和 padding 等,因?yàn)橄到y(tǒng)控件已經(jīng)幫我們做好了。

繼承已有布局

這種方式也叫做:自定義組合 View。該方式比較簡單,當(dāng)我們需要將一組 View 組合在一起,方便后期復(fù)用的時候,就可以使用該方法。當(dāng)我們使用這種方式的時候,不需要去處理 ViewGroup 的測量和布局流程,因?yàn)橄到y(tǒng)控件已經(jīng)幫我們做好了。

那么下面我們就從實(shí)例的角度來看看自定義View吧

繼承View的實(shí)例

當(dāng)我們自定義View繼承子View時,我們需要注意的細(xì)節(jié)有:1 View是wrap_content時需要手動測量View的寬高2 View有padding值的時候需要處理在這里我們寫一個規(guī)范的自定義View, 畫出一個圓注意: 要對 View 的 padding 和 LayoutParams 是 wrap_content 的情況進(jìn)行處理,否則 padding 將會無法生效、wrap_content 的效果會和 match_parent 一樣其中重寫onMeasure方法, 判斷當(dāng)是wrap_content的情況時,自己測量view的寬或高
package com.example.mycustomviewdemo;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.AttributeSet;import android.view.View;/** * 繼承View的自定義控件 * 注意 view是wrap_content時需要手動測量View的寬高 * View有padding值時需要處理 */public class MyCircleView extends View {    PRivate Paint mPaint;    private int mRadius;    public MyCircleView(Context context) {        this(context,null);    }    public MyCircleView(Context context, AttributeSet attrs) {        this(context, attrs,0);    }    public MyCircleView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        init();    }    private void init() {        mPaint = new Paint();   //初始化畫筆        mPaint.setColor(Color.GREEN);        mPaint.setAntiAlias(true);        mRadius = 80;    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, heightMeasureSpec);        int widthMode = MeasureSpec.getMode(widthMeasureSpec);        int heightMode = MeasureSpec.getMode(heightMeasureSpec);        int widthSize = MeasureSpec.getSize(widthMeasureSpec);        int heightSize = MeasureSpec.getSize(heightMeasureSpec);        int width = 0;        int height =0;        if(widthMode == MeasureSpec.EXACTLY) {            width = widthSize;        }else {            //widthMode == MeasureSpec.AT_MOST模式 自己設(shè)置控件寬度            //當(dāng)是wrap_content或者給具體dp的時候會走這里            width = mRadius * 2 +  getPaddingRight() + getPaddingLeft();        }        if(heightMode == MeasureSpec.EXACTLY) {            height = heightSize;        }else {            height = mRadius * 2 + getPaddingTop() + getPaddingBottom();        }        //注意最后 調(diào)用這個方法 讓屬性生效        setMeasuredDimension(width,height);    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        //處理padding        int pl = getPaddingLeft();        int pr = getPaddingRight();        int pt = getPaddingTop();        int pb = getPaddingBottom();        int width = getWidth() - pl - pr;  //控件本身的寬度        int height = getHeight() - pt - pb; //控件本身的高度        int centerX = width /2 + pl;  //中心點(diǎn)的橫坐標(biāo)        int centerY = height /2  + pt;  //中心點(diǎn)的縱坐標(biāo)        canvas.drawCircle(centerX,centerY,mRadius,mPaint);    }}

繼承ViewGroup實(shí)例

當(dāng)我們自定義View繼承自ViewGroup的時候,需要實(shí)現(xiàn)孩子的onLayout方法指定子View的擺放位置,并且需要重寫 onMeasure 方法來測量大小。在這個實(shí)例當(dāng)中,我們簡單模仿下 LinearLayout ,只不過只實(shí)現(xiàn)其 Vertical 模式,在這個實(shí)例當(dāng)中,我們需要注意的細(xì)節(jié)有:1 ViewGroup是wrap_content時需要手動測量2 當(dāng)ViewGroup本身有padding值的時候需要處理3 當(dāng)子View有margin值時需要處理規(guī)范自定義ViewGroup, 這幾個細(xì)節(jié)我們要處理,代碼:
package com.example.mycustomviewdemo;import android.content.Context;import android.util.AttributeSet;import android.view.View;import android.view.ViewGroup;/** * 繼承ViewGroup實(shí)例 * * 注意: * ViewGroup是wrap_content需要手動測量 * 當(dāng)ViewGroup本身有padding值時要處理 * 當(dāng)子view有margin值時要處理 */public class MySimpleVerticalLayout extends ViewGroup {    private Context mContext;    public MySimpleVerticalLayout(Context context) {        this(context,null);    }    public MySimpleVerticalLayout(Context context, AttributeSet attrs) {        this(context, attrs,0);    }    public MySimpleVerticalLayout(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        mContext = context;    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, heightMeasureSpec);        //獲取ViewGroup測量模式  大小        int widthMode = MeasureSpec.getMode(widthMeasureSpec);        int heightMode = MeasureSpec.getMode(heightMeasureSpec);        int widthSize = MeasureSpec.getSize(widthMeasureSpec);        int heightSize = MeasureSpec.getSize(heightMeasureSpec);        //獲取ViewGroup的padding(內(nèi)邊距)值        int pt = getPaddingTop();        int pb = getPaddingBottom();        int pl = getPaddingLeft();        int pr = getPaddingRight();        //先測量孩子, 才能得到孩子具體的寬高;    ------->> 這一步很重要        measureChildren(widthMeasureSpec,heightMeasureSpec);        int width = 0;        int height = 0;        int maxWidth = 0;        if(widthMode == MeasureSpec.AT_MOST) {            for(int i = 0; i < getChildCount();i++) {                View childAt = getChildAt(i);                if(childAt.getVisibility() == GONE) {                    continue;                }                //寬度為孩子中 最寬的一個                //孩子還有個MarginLayoutParams屬性                MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childAt.getLayoutParams();                int childWidth = childAt.getMeasuredWidth() + marginLayoutParams.leftMargin + marginLayoutParams.rightMargin;                maxWidth  = maxWidth > childWidth ? maxWidth : childWidth;            }            //將遍歷后的最寬的寬度加上左右內(nèi)邊距 賦值            width = maxWidth + pl + pr;        }        if(heightMode == MeasureSpec.AT_MOST) {            for(int i = 0; i < getChildCount();i++) {                View childAt = getChildAt(i);                if(childAt.getVisibility() == GONE) {                    continue;                }                //高度為所有的孩子高度之和加上內(nèi)邊距之和                MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childAt.getLayoutParams();                height += childAt.getMeasuredHeight() + marginLayoutParams.topMargin + marginLayoutParams.bottomMargin;            }            //最終的高度            height += (pt + pb);        }        //做判斷, 并將值設(shè)置        setMeasuredDimension(widthMode == MeasureSpec.AT_MOST ? width : widthSize,heightMode == MeasureSpec.AT_MOST ? height : heightSize);    }    /**     * 對子View進(jìn)行擺放     * @param changed     * @param l     * @param t     * @param r     * @param b     */    @Override    protected void onLayout(boolean changed, int l, int t, int r, int b) {        //viewGroup的padding值影響孩子的擺放        int pt = getPaddingTop();        int pb = getPaddingBottom();        int pl = getPaddingLeft();        int pr = getPaddingRight();        int cl = 0;        int ct = 0;        int cr = 0;        int cb = 0;        int bm = 0;     //這個bm很神奇        for(int i =0; i < getChildCount();i++) {            //判斷當(dāng)子view沒有被Gone掉時候            View childAt = getChildAt(i);            if(childAt.getVisibility() != GONE) {                //計算每個View的位置                MarginLayoutParams marginLayoutParams= (MarginLayoutParams) childAt.getLayoutParams();                cl = marginLayoutParams.leftMargin;                ct += marginLayoutParams.topMargin;                cr = childAt.getMeasuredWidth() + marginLayoutParams.leftMargin;                cb += childAt.getMeasuredHeight() + marginLayoutParams.topMargin;                //對子View進(jìn)行布局,  注意 一定要調(diào)用childAt.layout()方法                childAt.layout(cl + pl, ct + pt + bm, cr + pr,cb + pb + bm);                ct += childAt.getMeasuredHeight();                bm += marginLayoutParams.bottomMargin;            }        }    }    @Override    public LayoutParams generateLayoutParams(AttributeSet attrs) {        return new MarginLayoutParams(mContext, attrs);    }}

繼承已有View的實(shí)例

繼承自系統(tǒng)已有View時,一般是對其原有功能進(jìn)行擴(kuò)展或者修改, 比如一個Button  在這里注意監(jiān)聽器的使用

繼承已有ViewGroup的實(shí)例

這種自定義 View 的實(shí)現(xiàn)方式也叫做:“自定義組合控件”,是一種比較簡單的自定義 View 方式。使用這種方式時,由于是繼承已有的系統(tǒng)控件,所以我們不需去測量、布局、處理 margin、padding等,因?yàn)橄到y(tǒng)控件本身已經(jīng)處理好了。當(dāng)我們的項目中有一些布局在很多地方都要用到的話,那么第一時間肯定就要想到復(fù)用了。復(fù)用的話,有人可能會想到使用 include 復(fù)用布局,但是如果這樣的話,當(dāng)布局改動性很大時,使用 include 并不是很靈活。這時候,就可以使用 ”繼承已有 ViewGroup“ 這種方式了。下面一個實(shí)例,就拿我們平時可能經(jīng)常要寫的 Item 為例吧:
package com.example.mycustomviewdemo;import android.content.Context;import android.content.res.TypedArray;import android.util.AttributeSet;import android.view.LayoutInflater;import android.view.View;import android.widget.FrameLayout;import android.widget.ImageView;import android.widget.TextView;/** * 繼承已有的ViewGroup 自定義View的實(shí)例,常用item布局 */public class MyCustomItemLayout extends FrameLayout {    private Context mContext;    private String mLeftText;    private int mRightImageResourceId;    private String mRightText;    private TextView mTxt_left;    private TextView mTxt_right;    private ImageView mImg_right;    public void setLeftText(String leftText) {        mLeftText = leftText;    }    public void setRightImageResourceId(int rightImageResourceId) {        mRightImageResourceId = rightImageResourceId;    }    public void setRightText(String rightText) {        mRightText = rightText;    }    public MyCustomItemLayout(Context context) {        this(context,null);    }    public MyCustomItemLayout(Context context, AttributeSet attrs) {        this(context, attrs,0);    }    public MyCustomItemLayout(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        this.mContext = context;        //取出自定義屬性        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyCustomItemLayout);        mLeftText = typedArray.getString(R.styleable.MyCustomItemLayout_leftText);        //默認(rèn)圖片為箭頭        mRightImageResourceId = typedArray.getResourceId(R.styleable.MyCustomItemLayout_rightImage, R.drawable.ic_arrow_right);        mRightText = typedArray.getString(R.styleable.MyCustomItemLayout_rightText);        typedArray.recycle();  //回收釋放資源        initView();        initData();    }    private void initData() {        //兩種初始化數(shù)據(jù)的方法,  外界通過set方法進(jìn)行設(shè)置; 布局中直接定義        mTxt_left.setText(mLeftText);        mTxt_right.setText(mRightText);        mImg_right.setImageResource(mRightImageResourceId);    }    private void initView() {        //注意  這第二個參數(shù)傳 this;  兩個參數(shù)的方法默認(rèn)會調(diào)用三個參數(shù)的方法,  第二個參數(shù)不為null時,相當(dāng)于三個參數(shù)中root不為null,attach為true        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_customitem, this);        mTxt_left = (TextView) findViewById(R.id.txt_left);        mTxt_right = (TextView) findViewById(R.id.txt_right);        mImg_right = (ImageView) findViewById(R.id.img_right);    }}首先自定義一個類,繼承自 FrameLayout,當(dāng)然,這里你也可以選擇繼承 LinearLayout 或者其他,根據(jù)具體需求來。其中在構(gòu)造中獲取了自定義屬性,最主要的地方就是填充布局那里,將布局填充到了當(dāng)前控件也就是自定義的 ViewGroup 上。填充的布局如下:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:background="?android:selectableItemBackground"              android:gravity="center_vertical"              android:padding="15dp">    <TextView        android:id="@+id/txt_left"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:drawablePadding="5dp"        android:ellipsize="end"        android:maxLines="1"        android:textColor="@color/text_black"        android:textSize="@dimen/txt14"/>    <TextView        android:id="@+id/txt_right"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_marginLeft="10dp"        android:layout_weight="1"        android:ellipsize="end"        android:gravity="right"        android:maxLines="1"        android:textSize="@dimen/txt14"/>    <ImageView        android:id="@+id/img_right"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginLeft="5dp"        android:src="@mipmap/ic_arrow_right"/></LinearLayout>在項目中 有相類似的Item布局的使用時, 可以直接在布局中通過自定義屬性設(shè)置數(shù)據(jù):
<com.example.mycustomviewdemo.MyCustomItemLayout       android:layout_width="match_parent"       android:layout_height="wrap_content"       android:layout_marginTop="10dp"       app:leftText="版本更新"       app:rightText="V1.1"       app:rightImage="@drawable/ic_arrow_right"       />也可以通過暴露的方法設(shè)置數(shù)據(jù)至此,自定義控件四種繼承方式講解完畢,  下面看一三個自定義控件的效果
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 宜章县| 西丰县| 松江区| 昆山市| 南溪县| 西林县| 玉环县| 广州市| 托里县| 肥东县| 湖北省| 钟山县| 平凉市| 疏勒县| 轮台县| 乾安县| 临猗县| 视频| 南召县| 曲麻莱县| 黔西| 余庆县| 麻阳| 盘山县| 郑州市| 彰化市| 海门市| 华安县| 阳城县| 靖州| 三穗县| 金乡县| 顺平县| 阿拉尔市| 中方县| 青州市| 曲靖市| 昆山市| 绵阳市| 琼结县| 报价|