上一篇我們介紹了Android中自定義View的知識(shí)蚂且,并實(shí)現(xiàn)了一個(gè)類似Google彩虹進(jìn)度條的自定義View冬耿,今天我們將進(jìn)一步學(xué)習(xí)如何去自定義一個(gè)ViewGroup。
ViewGroup
我們知道ViewGroup就是View的容器類,我們經(jīng)常用的LinearLayout斟览,RelativeLayout等都是ViewGroup的子類,因?yàn)閂iewGroup有很多子View辑奈,所以它的整個(gè)繪制過(guò)程相對(duì)于View會(huì)復(fù)雜一點(diǎn)苛茂,但是還是三個(gè)步驟measure,layout鸠窗,draw妓羊,我們一次說(shuō)明。
-
Measure
Measure過(guò)程還是測(cè)量ViewGroup的大小稍计,如果layout_widht和layout_height是match_parent或具體的xxxdp躁绸,就很簡(jiǎn)答了,直接調(diào)用setMeasuredDimension()方法,設(shè)置ViewGroup的寬高即可净刮,如果是wrap_content剥哑,就比較麻煩了,我們需要遍歷所有的子View庭瑰,然后對(duì)每個(gè)子View進(jìn)行測(cè)量星持,然后根據(jù)子View的排列規(guī)則,計(jì)算出最終ViewGroup的大小弹灭。@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int childCount = this.getChildCount(); for (int i = 0; i < childCount; i++) { View child = this.getChildAt(i); this.measureChild(child, widthMeasureSpec, heightMeasureSpec); int cw = child.getMeasuredWidth(); // int ch = child.getMeasuredHeight(); } }
你可能需要類似上面的代碼督暂,其中g(shù)etChildCount()方法,返回子View的數(shù)量穷吮,measureChild()方法逻翁,調(diào)用子View的測(cè)量方法。
- Layout
上一篇中捡鱼,我們稍微提到了八回,layout過(guò)程其實(shí)就是對(duì)子View的位置進(jìn)行排列,onLayout方法給我一個(gè)機(jī)會(huì)驾诈,來(lái)按照我們想要的規(guī)則自定義子View排列缠诅。
@Override
protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
int childCount = this.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = this.getChildAt(i);
LayoutParams lParams = (LayoutParams) child.getLayoutParams();
child.layout(lParams.left, lParams.top, lParams.left + childWidth,
lParams.top + childHeight);
}
}
你同樣可能需要類似上面的代碼,其中child.layout(left,top,right,bottom)方法可以對(duì)子View的位置進(jìn)行設(shè)置乍迄,四個(gè)參數(shù)的意思大家通過(guò)變量名都應(yīng)該清楚了管引。 - Draw
ViewGroup在draw階段,其實(shí)就是按照子類的排列順序闯两,調(diào)用子類的onDraw方法褥伴,因?yàn)槲覀冎皇荲iew的容器, 本身一般不需要draw額外的修飾漾狼,所以往往在onDraw方法里面重慢,只需要調(diào)用ViewGroup的onDraw默認(rèn)實(shí)現(xiàn)方法即可。
LayoutParams
ViewGroup還有一個(gè)很重要的知識(shí)LayoutParams逊躁,LayoutParams存儲(chǔ)了子View在加入ViewGroup中時(shí)的一些參數(shù)信息似踱,在繼承ViewGroup類時(shí),一般也需要新建一個(gè)新的LayoutParams類稽煤,就像SDK中我們熟悉的LinearLayout.LayoutParams核芽,RelativeLayout.LayoutParams類等一樣,那么可以這樣做念脯,在你定義的ViewGroup子類中,新建一個(gè)LayoutParams類繼承與ViewGroup.LayoutParams弯淘。
public static class LayoutParams extends ViewGroup.LayoutParams {
public int left = 0;
public int top = 0;
public LayoutParams(Context arg0, AttributeSet arg1) {
super(arg0, arg1);
}
public LayoutParams(int arg0, int arg1) {
super(arg0, arg1);
}
public LayoutParams(android.view.ViewGroup.LayoutParams arg0) {
super(arg0);
}
}
那么現(xiàn)在新的LayoutParams類已經(jīng)有了绿店,如何讓我們自定義的ViewGroup使用我們自定義的LayoutParams類來(lái)添加子View呢,ViewGroup同樣提供了下面這幾個(gè)方法供我們重寫(xiě),我們重寫(xiě)返回我們自定義的LayoutParams對(duì)象即可假勿。
@Override
public android.view.ViewGroup.LayoutParams generateLayoutParams(
AttributeSet attrs) {
return new NinePhotoView.LayoutParams(getContext(), attrs);
}
@Override
protected android.view.ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
}
@Override
protected android.view.ViewGroup.LayoutParams generateLayoutParams(
android.view.ViewGroup.LayoutParams p) {
return new LayoutParams(p);
}
@Override
protected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams p) {
return p instanceof NinePhotoView.LayoutParams;
}
實(shí)例
我們還是做一個(gè)實(shí)例來(lái)說(shuō)明借嗽,我們今天做一個(gè)類似微信朋友圈 存儲(chǔ)要發(fā)送圖片的控件,點(diǎn)擊+號(hào)圖片转培,可以一直加圖片恶导,最多9張。那么微信是4個(gè)一排浸须,我們這里是3個(gè)一排惨寿,因?yàn)橐话愠R?guī)都是三個(gè)一排,這些都是細(xì)節(jié)不要在意(另外偷偷告訴大家删窒,微信的實(shí)現(xiàn)是用TableLayout裂垦,-.-)。
public class NinePhotoView extends ViewGroup {
public static final int MAX_PHOTO_NUMBER = 9;
private int[] constImageIds = { R.drawable.girl_0, R.drawable.girl_1,
R.drawable.girl_2, R.drawable.girl_3, R.drawable.girl_4,
R.drawable.girl_5, R.drawable.girl_6, R.drawable.girl_7,
R.drawable.girl_8 };
// horizontal space among children views
int hSpace = Utils.dpToPx(10, getResources());
// vertical space among children views
int vSpace = Utils.dpToPx(10, getResources());
// every child view width and height.
int childWidth = 0;
int childHeight = 0;
// store images res id
ArrayList<integer> mImageResArrayList = new ArrayList<integer>(9);
private View addPhotoView;
public NinePhotoView(Context context) {
super(context);
}
public NinePhotoView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public NinePhotoView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray t = context.obtainStyledAttributes(attrs,
R.styleable.NinePhotoView, 0, 0);
hSpace = t.getDimensionPixelSize(
R.styleable.NinePhotoView_ninephoto_hspace, hSpace);
vSpace = t.getDimensionPixelSize(
R.styleable.NinePhotoView_ninephoto_vspace, vSpace);
t.recycle();
addPhotoView = new View(context);
addView(addPhotoView);
mImageResArrayList.add(new integer());
}
目前為止肌索,都跟上一篇說(shuō)的大致差不多蕉拢,另外拍照和從相冊(cè)選擇圖片不是我們這一篇的重點(diǎn),所以我們把圖片硬編碼到代碼中(全是美女...),ViewGroup初始化時(shí)我們添加了一個(gè)+號(hào)按鈕诚亚,給用戶點(diǎn)擊添加新的圖片晕换。
-
Measure
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int rw = MeasureSpec.getSize(widthMeasureSpec);
int rh = MeasureSpec.getSize(heightMeasureSpec);childWidth = (rw - 2 * hSpace) / 3; childHeight = childWidth; int childCount = this.getChildCount(); for (int i = 0; i < childCount; i++) { View child = this.getChildAt(i); //this.measureChild(child, widthMeasureSpec, heightMeasureSpec); LayoutParams lParams = (LayoutParams) child.getLayoutParams(); lParams.left = (i % 3) * (childWidth + hSpace); lParams.top = (i / 3) * (childWidth + vSpace); } int vw = rw; int vh = rh; if (childCount < 3) { vw = childCount * (childWidth + hSpace); } vh = ((childCount + 3) / 3) * (childWidth + vSpace); setMeasuredDimension(vw, vh); }
我們的子View三個(gè)一排,而且都是正方形站宗,所以我們上面通過(guò)循環(huán)很好去得到所有子View的位置闸准,注意我們上面把子View的左上角坐標(biāo)存儲(chǔ)到我們自定義的LayoutParams 的left和top二個(gè)字段中,Layout階段會(huì)使用份乒,最后我們算得整個(gè)ViewGroup的寬高恕汇,調(diào)用setMeasuredDimension設(shè)置。
-
Layout
@Override
protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
int childCount = this.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = this.getChildAt(i);
LayoutParams lParams = (LayoutParams) child.getLayoutParams();
child.layout(lParams.left, lParams.top, lParams.left + childWidth,
lParams.top + childHeight);if (i == mImageResArrayList.size() - 1 && mImageResArrayList.size() != MAX_PHOTO_NUMBER) { child.setBackgroundResource(R.drawable.add_photo); child.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { addPhotoBtnClick(); } }); }else { child.setBackgroundResource(constImageIds[i]); child.setOnClickListener(null); } } } public void addPhoto() { if (mImageResArrayList.size() < MAX_PHOTO_NUMBER) { View newChild = new View(getContext()); addView(newChild); mImageResArrayList.add(new integer()); requestLayout(); invalidate(); } } public void addPhotoBtnClick() { final CharSequence[] items = { "Take Photo", "Photo from gallery" }; AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { addPhoto(); } }); builder.show(); }
最核心的就是調(diào)用layout方法或辖,根據(jù)我們measure階段獲得的LayoutParams中的left和top字段瘾英,也很好對(duì)每個(gè)子View進(jìn)行位置排列。然后判斷在圖片未達(dá)到最大值9張時(shí)颂暇,默認(rèn)最后一張是+號(hào)圖片缺谴,然后設(shè)置點(diǎn)擊事件,彈出對(duì)話框供用戶選擇操作耳鸯。
- Draw
不需要重寫(xiě)湿蛔,使用ViewGroup默認(rèn)實(shí)現(xiàn)即可。
附上布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="40dp"
android:orientation="vertical" >
<com.sw.demo.widget.NinePhotoView
android:id="@+id/photoview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:ninephoto_hspace="10dp"
app:ninephoto_vspace="10dp"
app:rainbowbar_color="@android:color/holo_blue_bright" >
</com.sw.demo.widget.NinePhotoView>
</LinearLayout>
最后還是加上程序運(yùn)行的效果圖县爬,今天自定義ViewGroup的講解就這么多了阳啥,祝大家每天都有新收獲,每天都有好心情~~~