整理自:
http://www.cnblogs.com/manuosex/p/5288191.html
最近一個項目里面要用到自定義View的技術,看了很多博客,準備在這里整理一下
首先,我把實現自己想要的View效果的方法分為3類:
-
自定義View
有多種實現方式:
Ⅰ、繼承現有控件,對其控件的功能進行拓展。
Ⅱ、將現有控件進行組合,實現功能更加強大控件。
Ⅲ、重寫View實現全新的控件
-
自定義ViewGroup
這個實際上就是我們自定義一個布局,我們在實際使用的時候依然要在這個自定義ViewGroup中加子元素(比如TextView、ImageView或者其他)
在開始講實現自定義View的方式之前,先了解一個基礎操作,有時我們看到在xml中使用自定義View時,可以添加自己的屬性,并且能夠與java建立聯系,這個即用到了:
零、自定義布局屬性:
首先我們需要在res/values/styles.xml文件(如果沒有請自己新建)里面聲明一個我們自定義的屬性:
<resources>
<!--name為聲明的"屬性集合"名,可以隨便取,但是最好是設置為跟我們的View一樣的名稱-->
<declare-styleable name="MyView">
<!--聲明我們的屬性,名稱為default_size,取值類型為尺寸類型(dp,px等)-->
<attr name="default_size" format="dimension" />
</declare-styleable>
</resources>
注意:需要在根標簽(LinearLayout)里面設定命名空間,命名空間名稱可以隨便取,比如hc,命名空間后面取得值是固定的:"http://schemas.android.com/apk/res-auto"
那么,這個自定屬性我們怎么在java代碼中真正地把它用起來呢?
在構造函數中,我們構造方法有個AttributeSet屬性,就是靠它幫我們把布局里面的屬性取出來:
private int defalutSize;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
//第二個參數就是我們在styles.xml文件中的<declare-styleable>標簽
//即屬性集合的標簽,在R文件中名稱為R.styleable+name
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);
//第一個參數為屬性集合里面的屬性,R文件名稱:R.styleable+屬性集合名稱+下劃線+屬性名稱
//第二個參數為,如果沒有設置這個屬性,則設置的默認的值
defalutSize = a.getDimensionPixelSize(R.styleable.MyView_default_size, 100);
//最后記得將TypedArray對象回收
a.recycle();
}
我們得到這個我們在xml中賦值的數據之后就可以拿它來做自己想做的事啦~~
下面就正式開始講自定義View實現方式啦
一、繼承現有控件,對其控件的功能進行拓展
這種自定義View方式難度最低,主要是重寫onDraw()方法,假設我們要實現下面的效果:
遇到這種情況,直接在TextView基礎上自定義即可,不需要完全自己從頭開始寫
onDraw()方法的核心是要會靈活運用Canvas和Paint,知道在哪個位置(getMeasuredWidth等獲取本控件位置的方法)用哪些效果(Canvas&Paint)在已有的控件上畫上自己想要的效果,里面詳細的內容這里就不講了,可以自己看原博主的博客看一下他是怎么實現的。
二、將現有控件進行組合,實現功能更加強大控件
這個需要我們組合已有的View來完成一個復雜功能,實際上我覺得這種方式實現自己想要的效果是最簡單的。
這種自定義View方法有幾個要點:
- 它要繼承的一般都是已有的布局,如LinearLayout或者RelativeLayout,看你自己想要實現的效果是怎樣的,如:
public class GeneralFrame extends LinearLayout{···}
這種自定義View方法也有2種做法來實現,先說第一種簡單一點的做法:
- 直接讀入已有的布局文件
比如我們要實現三國殺游戲武將的信息欄,里面包括武將頭像,血條,裝備區,這些元素以一種復雜的排列關系存在,我們呢不管這些,先寫一個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
//在構造函數中將Xml中定義的布局解析出來。
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)
{···}
這個做法非常簡單,我們最后只要留幾個接口給外部進行調用就可以了。
- 代碼中通過代碼動態生成自己想要的效果,用addView()加入到你自定義的View中。
我不得不說這個方法非常地麻煩,而且極容易出錯,我自己使用了一次之后就放棄了,下面來看看它的代碼就知道了
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);
}
}
這個只是非常簡單的布局效果,要是復雜起來簡直要炸,這個就權當了解即可···
三、重寫View實現全新的控件
這種方式適用于那種完全沒有參考的一種效果,比如支付寶的信用雷達圖之類的
這種方式需要重寫onMeasure、onLayout等方法,是最復雜的一種
下面也舉例說明:我們要實現一個圓形可以自定義顏色的view
分別重寫onMeasure和onDraw方法。
- 重寫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: {//如果沒有指定大小,就設置為默認大小
mySize = defaultSize;
break;
}
case MeasureSpec.AT_MOST: {//如果測量模式是最大取值為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傳進去的參數來自于xml的android:layout_width
和android:layout_height
<com.hc.studyview.MyView
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#ff0000" />
我們發現onMeasure中參數MeasureSpec.getMode得到的參數不是wrap_content或者match_parent這些值,這里面的對應關系又是怎樣的呢?
- match_parent—>EXACTLY。怎么理解呢?match_parent就是要利用父View給我們提供的所有剩余空間,而父View剩余空間是確定的,也就是這個測量模式的整數里面存放的尺寸。
- wrap_content—>AT_MOST。怎么理解:就是我們想要將大小設置為包裹我們的view內容,那么尺寸大小就是父View給我們作為參考的尺寸,只要不超過這個尺寸就可以啦,具體尺寸就根據我們的需求去設定。
- 固定尺寸(如100dp)—>EXACTLY。用戶自己指定了尺寸大小,我們就不用再去干涉了,當然是以指定的大小為主啦。
- 重寫onDraw()方法
在上面onMeasure的基礎上我們重寫onDraw,現在我們要把原來的正方形變成圓形,代碼如下:
@Override
protected void onDraw(Canvas canvas){
//調用父View的onDraw函數,因為View這個類幫我們實現了一些
// 基本的而繪制功能,比如繪制背景顏色、背景圖片等
super.onDraw(canvas);
int r = getMeasuredWidth() / 2;//也可以是getMeasuredHeight()/2,本例中我們已經將寬高設置相等了
//圓心的橫坐標為當前的View的左邊起始位置+半徑
int centerX = getLeft() + r;
//圓心的縱坐標為當前的View的頂部起始位置+半徑
int centerY = getTop() + r;
Paint paint = new Paint();
paint.setColor(Color.GREEN);
//開始繪制
canvas.drawCircle(centerX, centerY, r, paint);
}
注意這里父類的onDraw方法也放在里面,這個類幫我們實現了一些基本的繪制功能,比如繪制背景顏色、背景圖片等,這樣就算是完成這個可以自定義顏色的圓形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);
//第二個參數就是我們在styles.xml文件中的<declare-styleable>標簽
//即屬性集合的標簽,在R文件中名稱為R.styleable+name
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);
//第一個參數為屬性集合里面的屬性,R文件名稱:R.styleable+屬性集合名稱+下劃線+屬性名稱
//第二個參數為,如果沒有設置這個屬性,則設置的默認的值
defalutSize = a.getDimensionPixelSize(R.styleable.MyView_default_size, 100);
//最后記得將TypedArray對象回收
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: {//如果沒有指定大小,就設置為默認大小
mySize = defaultSize;
break;
}
case MeasureSpec.AT_MOST: {//如果測量模式是最大取值為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) {
//調用父View的onDraw函數,因為View這個類幫我們實現了一些
// 基本的而繪制功能,比如繪制背景顏色、背景圖片等
super.onDraw(canvas);
int r = getMeasuredWidth() / 2;//也可以是getMeasuredHeight()/2,本例中我們已經將寬高設置相等了
//圓心的橫坐標為當前的View的左邊起始位置+半徑
int centerX = getLeft() + r;
//圓心的縱坐標為當前的View的頂部起始位置+半徑
int centerY = getTop() + r;
Paint paint = new Paint();
paint.setColor(Color.GREEN);
//開始繪制
canvas.drawCircle(centerX, centerY, r, paint);
}
}