編輯:Android 開發教學

要做一個「最多九張圖、點最後一格加圖」的九宮格,用 ViewGroup 自己算座標比硬套 GridView 更可控。以下一步步拆解。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://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>
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
};
// 子 View 之間的水平間距
int hSpace = Utils.dpToPx(10, getResources());
// 子 View 之間的垂直間距
int vSpace = Utils.dpToPx(10, getResources());
// 每個子 View 的寬高(正方形)
int childWidth = 0;
int childHeight = 0;
// 存放圖片資源 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());
}
@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);
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 三個一排、每格都是正方形,所以位置可以直接用除餘算出:欄號是 i % 3,列號是 i / 3。這裡刻意把左上角座標存進自定義 LayoutParams 的 left 與 top 欄位,留給 layout 階段使用;最後再算出整個 ViewGroup 的寬高並呼叫 setMeasuredDimension 設定。
@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();
}
核心就是呼叫 layout 時,依 measure 階段算好的 left 與 top 把每個子 View 放上去。接著判斷:圖片數未達九張時,最後一格固定是「+」號並綁定點擊事件,點下去彈出對話框讓使用者選拍照或相簿;已滿九張則全部顯示圖片、取消點擊。
不需要覆寫,使用 ViewGroup 的預設實作即可——這個自定義容器只在 onMeasure 與 onLayout 上做功夫,繪製交給各子 View 自己處理。
實際操作效果:

自定義 View 探索(一):用日誌實際跑一遍 View 的生命週期
自定義 View 最怕「憑感覺猜執行順序」。最直接的解法是在每個回呼裡都打一行 log,跑一次,順序自然清楚。以下就用這個笨但有效的方法,把 View 從建立到顯示的過程
Android 測試教程(3):測試專案的組織結構
Android 的編譯與測試工具對測試專案的組織方式有既定要求,基本上分為三層:測試案例類別、測試案例套件,以及測試專案本身。 JUnit 的三層結構 JUnit 是 A
ApiDemos 解析(10):用 Content Provider 讀取聯絡人
QuickContactsDemo 示範如何透過 Content Provider 存取 Android 系統的聯絡人資料庫。 Content Provider 的定位
用 dom4j 建立與解析 XML(Android 系列之五)
在 Java 生態系中處理 XML,dom4j 是相當經典的選擇。它是一個開源、易用的程式庫,支援 XML、XPath 與 XSLT,並建立在 Java Collecti