實(shí)現(xiàn)自己想要的View效果(1):自定義View

整理自:
http://www.cnblogs.com/manuosex/p/5288191.html


最近一個(gè)項(xiàng)目里面要用到自定義View的技術(shù),看了很多博客,準(zhǔn)備在這里整理一下
首先,我把實(shí)現(xiàn)自己想要的View效果的方法分為3類:

  1. 自定義View

有多種實(shí)現(xiàn)方式:
Ⅰ、繼承現(xiàn)有控件,對(duì)其控件的功能進(jìn)行拓展。
Ⅱ、將現(xiàn)有控件進(jìn)行組合,實(shí)現(xiàn)功能更加強(qiáng)大控件。
Ⅲ、重寫View實(shí)現(xiàn)全新的控件

  1. 自定義ViewGroup

這個(gè)實(shí)際上就是我們自定義一個(gè)布局,我們?cè)趯?shí)際使用的時(shí)候依然要在這個(gè)自定義ViewGroup中加子元素(比如TextView、ImageView或者其他)


在開(kāi)始講實(shí)現(xiàn)自定義View的方式之前,先了解一個(gè)基礎(chǔ)操作,有時(shí)我們看到在xml中使用自定義View時(shí),可以添加自己的屬性,并且能夠與java建立聯(lián)系,這個(gè)即用到了:

零、自定義布局屬性

首先我們需要在res/values/styles.xml文件(如果沒(méi)有請(qǐng)自己新建)里面聲明一個(gè)我們自定義的屬性:

<resources>
    <!--name為聲明的"屬性集合"名,可以隨便取,但是最好是設(shè)置為跟我們的View一樣的名稱-->
    <declare-styleable name="MyView">
        <!--聲明我們的屬性,名稱為default_size,取值類型為尺寸類型(dp,px等)-->
        <attr name="default_size" format="dimension" />
    </declare-styleable>
</resources>

注意:需要在根標(biāo)簽(LinearLayout)里面設(shè)定命名空間,命名空間名稱可以隨便取,比如hc,命名空間后面取得值是固定的:"http://schemas.android.com/apk/res-auto"

那么,這個(gè)自定屬性我們?cè)趺丛趈ava代碼中真正地把它用起來(lái)呢?
在構(gòu)造函數(shù)中,我們構(gòu)造方法有個(gè)AttributeSet屬性,就是靠它幫我們把布局里面的屬性取出來(lái):

 private int defalutSize;
  public MyView(Context context, AttributeSet attrs) {
      super(context, attrs);
      //第二個(gè)參數(shù)就是我們?cè)趕tyles.xml文件中的<declare-styleable>標(biāo)簽
        //即屬性集合的標(biāo)簽,在R文件中名稱為R.styleable+name
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);

        //第一個(gè)參數(shù)為屬性集合里面的屬性,R文件名稱:R.styleable+屬性集合名稱+下劃線+屬性名稱
        //第二個(gè)參數(shù)為,如果沒(méi)有設(shè)置這個(gè)屬性,則設(shè)置的默認(rèn)的值
        defalutSize = a.getDimensionPixelSize(R.styleable.MyView_default_size, 100);

        //最后記得將TypedArray對(duì)象回收
        a.recycle();
   }

我們得到這個(gè)我們?cè)趚ml中賦值的數(shù)據(jù)之后就可以拿它來(lái)做自己想做的事啦~~


下面就正式開(kāi)始講自定義View實(shí)現(xiàn)方式啦


一、繼承現(xiàn)有控件,對(duì)其控件的功能進(jìn)行拓展

這種自定義View方式難度最低,主要是重寫onDraw()方法,假設(shè)我們要實(shí)現(xiàn)下面的效果:


我們要實(shí)現(xiàn)的效果

遇到這種情況,直接在TextView基礎(chǔ)上自定義即可,不需要完全自己從頭開(kāi)始寫
onDraw()方法的核心是要會(huì)靈活運(yùn)用Canvas和Paint,知道在哪個(gè)位置(getMeasuredWidth等獲取本控件位置的方法)用哪些效果(Canvas&Paint)在已有的控件上畫上自己想要的效果,里面詳細(xì)的內(nèi)容這里就不講了,可以自己看原博主的博客看一下他是怎么實(shí)現(xiàn)的。

二、將現(xiàn)有控件進(jìn)行組合,實(shí)現(xiàn)功能更加強(qiáng)大控件

這個(gè)需要我們組合已有的View來(lái)完成一個(gè)復(fù)雜功能,實(shí)際上我覺(jué)得這種方式實(shí)現(xiàn)自己想要的效果是最簡(jiǎn)單的。
這種自定義View方法有幾個(gè)要點(diǎn):

  • 它要繼承的一般都是已有的布局,如LinearLayout或者RelativeLayout,看你自己想要實(shí)現(xiàn)的效果是怎樣的,如:public class GeneralFrame extends LinearLayout{···}

這種自定義View方法也有2種做法來(lái)實(shí)現(xiàn),先說(shuō)第一種簡(jiǎn)單一點(diǎn)的做法:

  1. 直接讀入已有的布局文件
    比如我們要實(shí)現(xiàn)三國(guó)殺游戲武將的信息欄,里面包括武將頭像,血條,裝備區(qū),這些元素以一種復(fù)雜的排列關(guān)系存在,我們呢不管這些,先寫一個(gè)R.layout布局文件:
<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:orientation="horizontal" >
     <LinearLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:orientation="vertical"
         >
         <ImageView
             android:id="@+id/touxiang"
             android:layout_width="80dp"
             android:layout_height="80dp"
             android:maxWidth="80dp"
             android:maxHeight="80dp"    
             >
         </ImageView>
         <ImageView
             android:id="@+id/blood"
             android:layout_width="wrap_content"
         android:layout_height="wrap_content"
             android:maxWidth="80dp"
             android:maxHeight="20dp"
             >            
         </ImageView>
         
     </LinearLayout>
     
     <LinearLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:orientation="vertical"
         android:layout_gravity="center_vertical"
         >
         <TextView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="武器"
             ></TextView>
         <TextView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="防具"
             ></TextView>
         <TextView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="+1馬"
             ></TextView>
         <TextView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="-1馬"
             ></TextView>
     </LinearLayout>
 
 </LinearLayout>

然后在自定義View里面:

public class GeneralFrame extends LinearLayout {
    ImageView general;
    ImageView blood;
    TextView wuqi;
    TextView fangju;
    TextView jiayima;
    TextView jianyima;
    public GeneralFrame(Context context) {
        //super(context);
        // TODO Auto-generated constructor stub
        this(context,null);
    }
    public GeneralFrame(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        //在構(gòu)造函數(shù)中將Xml中定義的布局解析出來(lái)。   
        LayoutInflater mInflater = LayoutInflater.from(context);  
        View myView = mInflater.inflate(R.layout.receive, null);  
        addView(myView); 
        general=(ImageView)findViewById(R.id.touxiang);
        blood=(ImageView)findViewById(R.id.blood);
        blood.setImageResource(R.drawable.blood);
        //wuqi=(TextView)findViewById(R.id
    }
  public void setImageResource(int Res)
  {···}

這個(gè)做法非常簡(jiǎn)單,我們最后只要留幾個(gè)接口給外部進(jìn)行調(diào)用就可以了。

  1. 代碼中通過(guò)代碼動(dòng)態(tài)生成自己想要的效果,用addView()加入到你自定義的View中。
    我不得不說(shuō)這個(gè)方法非常地麻煩,而且極容易出錯(cuò),我自己使用了一次之后就放棄了,下面來(lái)看看它的代碼就知道了
private class SpeechView extends LinearLayout {     
        private TextView mTitle;    
        private TextView mDialogue;    
        public SpeechView(Context context, String title, String words) {    
            super(context);    
            this.setOrientation(VERTICAL);    
             // Here we build the child views in code. They could also have    
            // been specified in an XML file.  
            mTitle = new TextView(context);  
            mTitle.setText(title);    
            addView(mTitle, new LinearLayout.LayoutParams(    
            LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));  
            mDialogue = new TextView(context);    
            mDialogue.setText(words);   
            addView(mDialogue, new LinearLayout.LayoutParams(  
            LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));  
       }  
       public void setTitle(String title) {    
            mTitle.setText(title);    
       }         
      public void setDialogue(String words) {  
        mDialogue.setText(words);   
       }    
}   

這個(gè)只是非常簡(jiǎn)單的布局效果,要是復(fù)雜起來(lái)簡(jiǎn)直要炸,這個(gè)就權(quán)當(dāng)了解即可···

三、重寫View實(shí)現(xiàn)全新的控件

這種方式適用于那種完全沒(méi)有參考的一種效果,比如支付寶的信用雷達(dá)圖之類的
這種方式需要重寫onMeasure、onLayout等方法,是最復(fù)雜的一種
下面也舉例說(shuō)明:我們要實(shí)現(xiàn)一個(gè)圓形可以自定義顏色的view

要實(shí)現(xiàn)的效果

分別重寫onMeasure和onDraw方法。

  1. 重寫onMeasure方法:
 private int getMySize(int defaultSize, int measureSpec) {
        int mySize = defaultSize;

        int mode = MeasureSpec.getMode(measureSpec);
        int size = MeasureSpec.getSize(measureSpec);

        switch (mode) {
            case MeasureSpec.UNSPECIFIED: {//如果沒(méi)有指定大小,就設(shè)置為默認(rèn)大小
                mySize = defaultSize;
                break;
            }
            case MeasureSpec.AT_MOST: {//如果測(cè)量模式是最大取值為size
                //我們將大小取最大值,你也可以取其他值
                mySize = size;
                break;
            }
            case MeasureSpec.EXACTLY: {//如果是固定的大小,那就不要去改變它
                mySize = size;
                break;
            }
        }
        return mySize;}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getMySize(100, widthMeasureSpec);
        int height = getMySize(100, heightMeasureSpec);

        if (width < height) {
            height = width;
        } else {
            width = height;
        }

        setMeasuredDimension(width, height);
}

這里onMeasure傳進(jìn)去的參數(shù)來(lái)自于xml的android:layout_width
android:layout_height

<com.hc.studyview.MyView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="#ff0000" />
使用了我們自己定義的onMeasure函數(shù)后的效果

不重寫onMeasure

我們發(fā)現(xiàn)onMeasure中參數(shù)MeasureSpec.getMode得到的參數(shù)不是wrap_content或者match_parent這些值,這里面的對(duì)應(yīng)關(guān)系又是怎樣的呢?

  1. match_parent—>EXACTLY。怎么理解呢?match_parent就是要利用父View給我們提供的所有剩余空間,而父View剩余空間是確定的,也就是這個(gè)測(cè)量模式的整數(shù)里面存放的尺寸。
  2. wrap_content—>AT_MOST。怎么理解:就是我們想要將大小設(shè)置為包裹我們的view內(nèi)容,那么尺寸大小就是父View給我們作為參考的尺寸,只要不超過(guò)這個(gè)尺寸就可以啦,具體尺寸就根據(jù)我們的需求去設(shè)定。
  3. 固定尺寸(如100dp)—>EXACTLY。用戶自己指定了尺寸大小,我們就不用再去干涉了,當(dāng)然是以指定的大小為主啦。
  1. 重寫onDraw()方法
    在上面onMeasure的基礎(chǔ)上我們重寫onDraw,現(xiàn)在我們要把原來(lái)的正方形變成圓形,代碼如下:
@Override
    protected void onDraw(Canvas canvas){
        //調(diào)用父View的onDraw函數(shù),因?yàn)閂iew這個(gè)類幫我們實(shí)現(xiàn)了一些
        // 基本的而繪制功能,比如繪制背景顏色、背景圖片等
        super.onDraw(canvas);
        int r = getMeasuredWidth() / 2;//也可以是getMeasuredHeight()/2,本例中我們已經(jīng)將寬高設(shè)置相等了
        //圓心的橫坐標(biāo)為當(dāng)前的View的左邊起始位置+半徑
        int centerX = getLeft() + r;
        //圓心的縱坐標(biāo)為當(dāng)前的View的頂部起始位置+半徑
        int centerY = getTop() + r;
        Paint paint = new Paint();
        paint.setColor(Color.GREEN);
        //開(kāi)始繪制
        canvas.drawCircle(centerX, centerY, r, paint);
    }

注意這里父類的onDraw方法也放在里面,這個(gè)類幫我們實(shí)現(xiàn)了一些基本的繪制功能,比如繪制背景顏色、背景圖片等,這樣就算是完成這個(gè)可以自定義顏色的圓形View的自定義了。

最后附上完整代碼:

/**
 * Package com.hc.studyview
 * Created by HuaChao on 2016/6/3.
 */
public class MyView extends View {

    private int defalutSize;

    public MyView(Context context) {
        super(context);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //第二個(gè)參數(shù)就是我們?cè)趕tyles.xml文件中的<declare-styleable>標(biāo)簽
        //即屬性集合的標(biāo)簽,在R文件中名稱為R.styleable+name
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        //第一個(gè)參數(shù)為屬性集合里面的屬性,R文件名稱:R.styleable+屬性集合名稱+下劃線+屬性名稱
        //第二個(gè)參數(shù)為,如果沒(méi)有設(shè)置這個(gè)屬性,則設(shè)置的默認(rèn)的值
        defalutSize = a.getDimensionPixelSize(R.styleable.MyView_default_size, 100);
        //最后記得將TypedArray對(duì)象回收
        a.recycle();
    }


    private int getMySize(int defaultSize, int measureSpec) {
        int mySize = defaultSize;

        int mode = MeasureSpec.getMode(measureSpec);
        int size = MeasureSpec.getSize(measureSpec);

        switch (mode) {
            case MeasureSpec.UNSPECIFIED: {//如果沒(méi)有指定大小,就設(shè)置為默認(rèn)大小
                mySize = defaultSize;
                break;
            }
            case MeasureSpec.AT_MOST: {//如果測(cè)量模式是最大取值為size
                //我們將大小取最大值,你也可以取其他值
                mySize = size;
                break;
            }
            case MeasureSpec.EXACTLY: {//如果是固定的大小,那就不要去改變它
                mySize = size;
                break;
            }
        }
        return mySize;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getMySize(defalutSize, widthMeasureSpec);
        int height = getMySize(defalutSize, heightMeasureSpec);

        if (width < height) {
            height = width;
        } else {
            width = height;
        }

        setMeasuredDimension(width, height);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        //調(diào)用父View的onDraw函數(shù),因?yàn)閂iew這個(gè)類幫我們實(shí)現(xiàn)了一些
        // 基本的而繪制功能,比如繪制背景顏色、背景圖片等
        super.onDraw(canvas);
        int r = getMeasuredWidth() / 2;//也可以是getMeasuredHeight()/2,本例中我們已經(jīng)將寬高設(shè)置相等了
        //圓心的橫坐標(biāo)為當(dāng)前的View的左邊起始位置+半徑
        int centerX = getLeft() + r;
        //圓心的縱坐標(biāo)為當(dāng)前的View的頂部起始位置+半徑
        int centerY = getTop() + r;

        Paint paint = new Paint();
        paint.setColor(Color.GREEN);
        //開(kāi)始繪制
        canvas.drawCircle(centerX, centerY, r, paint);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容