android 自定義控件的兩種做法

出處:http://blog.csdn.net/lmj623565791/article/details/24252901

第一種,集成view,控件的樣式自己畫:

很多的Android入門程序猿來說對於Android自定義View,可能都是比較恐懼的,但是這又是高手進階的必經之路,所有準備在自定義View上面花一些功夫,多寫一些文章。先總結下自定義View的步驟:

1、自定義View的屬性

2、在View的構造方法中獲得我們自定義的屬性

[ 3、重寫onMesure ]

4、重寫onDraw

我把3用[]標出了,所以說3不一定是必須的,當然了大部分情況下還是需要重寫的。

1、自定義View的屬性,首先在res/values/  下建立一個attrs.xml , 在裏面定義我們的屬性和聲明我們的整個樣式。

[html] view plain copy 在CODE上查看代碼片派生到我的代碼片

  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <resources>  

  3.   

  4.     <attr name="titleText" format="string" />  

  5.     <attr name="titleTextColor" format="color" />  

  6.     <attr name="titleTextSize" format="dimension" />  

  7.   

  8.     <declare-styleable name="CustomTitleView">  

  9.         <attr name="titleText" />  

  10.         <attr name="titleTextColor" />  

  11.         <attr name="titleTextSize" />  

  12.     </declare-styleable>  

  13.   

  14. </resources>  

我們定義了字體,字體顏色,字體大小3個屬性,format是值該屬性的取值類型:


一共有:string,color,demension,integer,enum,reference,float,boolean,fraction,flag;不清楚的可以google一把。

然後在佈局中聲明我們的自定義View


[objc] view plain copy 在CODE上查看代碼片派生到我的代碼片

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  

  2.     xmlns:tools="http://schemas.android.com/tools"  

  3.     xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01"  

  4.     android:layout_width="match_parent"  

  5.     android:layout_height="match_parent" >  

  6.   

  7.     <com.example.customview01.view.CustomTitleView  

  8.         android:layout_width="200dp"  

  9.         android:layout_height="100dp"  

  10.         custom:titleText="3712"  

  11.         custom:titleTextColor="#ff0000"  

  12.         custom:titleTextSize="40sp" />  

  13.   

  14. </RelativeLayout>  


一定要引入 xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01"我們的命名空間,後面的包路徑指的是項目的package


2、在View的構造方法中,獲得我們的自定義的樣式


[java] view plain copy 在CODE上查看代碼片派生到我的代碼片

  1. /** 

  2.      * 文本 

  3.      */  

  4.     private String mTitleText;  

  5.     /** 

  6.      * 文本的顏色 

  7.      */  

  8.     private int mTitleTextColor;  

  9.     /** 

  10.      * 文本的大小 

  11.      */  

  12.     private int mTitleTextSize;  

  13.   

  14.     /** 

  15.      * 繪製時控制文本繪製的範圍 

  16.      */  

  17.     private Rect mBound;  

  18.     private Paint mPaint;  

  19.   

  20.     public CustomTitleView(Context context, AttributeSet attrs)  

  21.     {  

  22.         this(context, attrs, 0);  

  23.     }  

  24.   

  25.     public CustomTitleView(Context context)  

  26.     {  

  27.         this(context, null);  

  28.     }  

  29.   

  30.     /** 

  31.      * 獲得我自定義的樣式屬性 

  32.      *  

  33.      * @param context 

  34.      * @param attrs 

  35.      * @param defStyle 

  36.      */  

  37.     public CustomTitleView(Context context, AttributeSet attrs, int defStyle)  

  38.     {  

  39.         super(context, attrs, defStyle);  

  40.         /** 

  41.          * 獲得我們所定義的自定義樣式屬性 

  42.          */  

  43.         TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomTitleView, defStyle, 0);  

  44.         int n = a.getIndexCount();  

  45.         for (int i = 0; i < n; i++)  

  46.         {  

  47.             int attr = a.getIndex(i);  

  48.             switch (attr)  

  49.             {  

  50.             case R.styleable.CustomTitleView_titleText:  

  51.                 mTitleText = a.getString(attr);  

  52.                 break;  

  53.             case R.styleable.CustomTitleView_titleTextColor:  

  54.                 // 默認顏色設置爲黑色  

  55.                 mTitleTextColor = a.getColor(attr, Color.BLACK);  

  56.                 break;  

  57.             case R.styleable.CustomTitleView_titleTextSize:  

  58.                 // 默認設置爲16sp,TypeValue也可以把sp轉化爲px  

  59.                 mTitleTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(  

  60.                         TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));  

  61.                 break;  

  62.   

  63.             }  

  64.   

  65.         }  

  66.         a.recycle();  

  67.   

  68.         /** 

  69.          * 獲得繪製文本的寬和高 

  70.          */  

  71.         mPaint = new Paint();  

  72.         mPaint.setTextSize(mTitleTextSize);  

  73.         // mPaint.setColor(mTitleTextColor);  

  74.         mBound = new Rect();  

  75.         mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);  

  76.   

  77.     }  


我們重寫了3個構造方法,默認的佈局文件調用的是兩個參數的構造方法,所以記得讓所有的構造調用我們的三個參數的構造,我們在三個參數的構造中獲得自定義屬性。


3、我們重寫onDraw,onMesure調用系統提供的:


[java] view plain copy 在CODE上查看代碼片派生到我的代碼片

  1. @Override  

  2.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  

  3.     {  

  4.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  

  5.     }  

  6.   

  7.     @Override  

  8.     protected void onDraw(Canvas canvas)  

  9.     {  

  10.         mPaint.setColor(Color.YELLOW);  

  11.         canvas.drawRect(00, getMeasuredWidth(), getMeasuredHeight(), mPaint);  

  12.   

  13.         mPaint.setColor(mTitleTextColor);  

  14.         canvas.drawText(mTitleText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint);  

  15.     }  

此時的效果是:


是不是覺得還不錯,基本已經實現了自定義View。但是此時如果我們把佈局文件的寬和高寫成wrap_content,會發現效果並不是我們的預期:


系統幫我們測量的高度和寬度都是MATCH_PARNET,當我們設置明確的寬度和高度時,系統幫我們測量的結果就是我們設置的結果,當我們設置爲WRAP_CONTENT,或者MATCH_PARENT系統幫我們測量的結果就是MATCH_PARENT的長度。

所以,當設置了WRAP_CONTENT時,我們需要自己進行測量,即重寫onMesure方法”:

重寫之前先了解MeasureSpec的specMode,一共三種類型:

EXACTLY:一般是設置了明確的值或者是MATCH_PARENT

AT_MOST:表示子佈局限制在一個最大值內,一般爲WARP_CONTENT

UNSPECIFIED:表示子佈局想要多大就多大,很少使用

下面是我們重寫onMeasure代碼:


[java] view plain copy 在CODE上查看代碼片派生到我的代碼片

  1. @Override  

  2. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  

  3. {  

  4.     int widthMode = MeasureSpec.getMode(widthMeasureSpec);  

  5.     int widthSize = MeasureSpec.getSize(widthMeasureSpec);  

  6.     int heightMode = MeasureSpec.getMode(heightMeasureSpec);  

  7.     int heightSize = MeasureSpec.getSize(heightMeasureSpec);  

  8.     int width;  

  9.     int height ;  

  10.     if (widthMode == MeasureSpec.EXACTLY)  

  11.     {  

  12.         width = widthSize;  

  13.     } else  

  14.     {  

  15.         mPaint.setTextSize(mTitleTextSize);  

  16.         mPaint.getTextBounds(mTitle, 0, mTitle.length(), mBounds);  

  17.         float textWidth = mBounds.width();  

  18.         int desired = (int) (getPaddingLeft() + textWidth + getPaddingRight());  

  19.         width = desired;  

  20.     }  

  21.   

  22.     if (heightMode == MeasureSpec.EXACTLY)  

  23.     {  

  24.         height = heightSize;  

  25.     } else  

  26.     {  

  27.         mPaint.setTextSize(mTitleTextSize);  

  28.         mPaint.getTextBounds(mTitle, 0, mTitle.length(), mBounds);  

  29.         float textHeight = mBounds.height();  

  30.         int desired = (int) (getPaddingTop() + textHeight + getPaddingBottom());  

  31.         height = desired;  

  32.     }  

  33.       

  34.       

  35.   

  36.     setMeasuredDimension(width, height);  

  37. }  


現在我們修改下佈局文件:



[html] view plain copy 在CODE上查看代碼片派生到我的代碼片

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  

  2.     xmlns:tools="http://schemas.android.com/tools"  

  3.     xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01"  

  4.     android:layout_width="match_parent"  

  5.     android:layout_height="match_parent" >  

  6.   

  7.     <com.example.customview01.view.CustomTitleView  

  8.         android:layout_width="wrap_content"  

  9.         android:layout_height="wrap_content"  

  10.         custom:titleText="3712"  

  11.         android:padding="10dp"  

  12.         custom:titleTextColor="#ff0000"  

  13.         android:layout_centerInParent="true"  

  14.         custom:titleTextSize="40sp" />  

  15.   

  16. </RelativeLayout>  


現在的效果是:



完全複合我們的預期,現在我們可以對高度、寬度進行隨便的設置了,基本可以滿足我們的需求。

當然了,這樣下來我們這個自定義View與TextView相比豈不是沒什麼優勢,所有我們覺得給自定義View添加一個事件:

在構造中添加:


[java] view plain copy 在CODE上查看代碼片派生到我的代碼片

  1. this.setOnClickListener(new OnClickListener()  

  2.         {  

  3.   

  4.             @Override  

  5.             public void onClick(View v)  

  6.             {  

  7.                 mTitleText = randomText();  

  8.                 postInvalidate();  

  9.             }  

  10.   

  11.         });  


[java] view plain copy 在CODE上查看代碼片派生到我的代碼片

  1. private String randomText()  

  2.     {  

  3.         Random random = new Random();  

  4.         Set<Integer> set = new HashSet<Integer>();  

  5.         while (set.size() < 4)  

  6.         {  

  7.             int randomInt = random.nextInt(10);  

  8.             set.add(randomInt);  

  9.         }  

  10.         StringBuffer sb = new StringBuffer();  

  11.         for (Integer i : set)  

  12.         {  

  13.             sb.append("" + i);  

  14.         }  

  15.   

  16.         return sb.toString();  

  17.     }  


下面再來運行:



我們添加了一個點擊事件,每次讓它隨機生成一個4位的隨機數。

第二種:繼承已有的view,如relationlayout、Framelayout,然後添加已寫好的xml佈局。代碼如下

1、控件代碼

package com.example.view;

import android.annotation.SuppressLint;

import android.content.Context;

import android.util.AttributeSet;

import android.view.LayoutInflater;

import android.view.View;

import android.widget.LinearLayout;

import android.widget.Toast;


public class MyBottomBar extends LinearLayout {


private Context mContext;

private View mLayout;

private View mBtn0, mBtn1, mBtn2, mBtn3;


public MyBottomBar(Context context, AttributeSet attrs) {

this(context, attrs, 0);

// TODO Auto-generated constructor stub

}


public MyBottomBar(Context context) {

this(context, null);

// TODO Auto-generated constructor stub

}


@SuppressLint("NewApi")

public MyBottomBar(Context context, AttributeSet attrs, int arg2) {

super(context, attrs, arg2);

this.mContext = context;

init();


}


private void init() {

            //mLayout是將要添加的佈局

mLayout = LayoutInflater.from(mContext).inflate(R.layout.bottom_layout,

null);

mBtn0 = mLayout.findViewById(R.id.btn0);

mBtn1 = mLayout.findViewById(R.id.btn1);

mBtn2 = mLayout.findViewById(R.id.btn2);

mBtn3 = mLayout.findViewById(R.id.btn3);

                 //添加事件

mBtn0.setOnClickListener(onclick);

mBtn1.setOnClickListener(onclick);

mBtn2.setOnClickListener(onclick);

mBtn3.setOnClickListener(onclick);

                //加入佈局中

addView(mLayout);

setHorizontalGravity(HORIZONTAL);

}

String mStr=null;

OnClickListener onclick = new OnClickListener() {


@Override

public void onClick(View v) {

switch (v.getId()) { 

case R.id.btn0:

mStr = "您點擊了btn0,childCount="+getChildCount();

toastUtils(mStr);

break;

case R.id.btn1:

mStr = "您點擊了btn1,childCount="+getChildCount();

toastUtils(mStr);

break;

case R.id.btn2:

mStr = "您點擊了btn2,childCount="+getChildCount();

toastUtils(mStr);

break;

case R.id.btn3:

mStr = "您點擊了btn3,childCount="+getChildCount();

toastUtils(mStr);

break;

default:

break;

}

}

};


private void toastUtils(String msg) {

Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();

}

}

2、xml佈局代碼:

<?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="match_parent"

    android:gravity="center_horizontal"

    android:orientation="horizontal" >


    <Button

        android:id="@+id/btn0"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Button0" />


    <Button

        android:id="@+id/btn1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Button1" />


    <Button

        android:id="@+id/btn2"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Button2" />


    <Button

        android:id="@+id/btn3"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Button3" />


</LinearLayout>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章