Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自定義 ViewGroup 實作 CustomGridLayout(一)

編輯:關於 Android 程式設計

前兩篇寫了自定義 View 的基礎,這篇進入自定義 ViewGroup。

ViewGroup 顧名思義就是 View 的容器,我們常用的 LinearLayout、RelativeLayout 都是它的子類。寫版面 XML 時,凡是 layout_ 開頭的屬性都是在跟容器溝通:layout_width、layout_height 告訴容器我想要的尺寸,layout_gravity 告訴容器我想到的位置。

所以 ViewGroup 的職責可以歸納為兩件事:為子 View 計算建議的寬高與測量模式,並決定子 View 的實際位置。之所以只是「建議」,是因為子 View 的寬高可能設為 wrap_content,這時唯有子 View 自己才能算出最終尺寸。

流程上,View 依 ViewGroup 傳入的測量值與模式決定自身寬高(onMeasure),再在 onDraw 中完成繪製;ViewGroup 則要為每個子 View 提供測量規格(onMeasure),同時也要確定自己的寬高(onMeasure),最後在 onLayout 中指定所有子 View 的位置。

由於 ViewGroup 管理多個子 View,整個流程比單一 View 複雜,但依然遵循 measure → layout → draw 三步。本文就來做一個類似 GridView 的網格容器,姑且稱作 CustomGridLayout。

一、自定義屬性

<resources>
    <declare-styleable name="CustomGridView">
        <attr name="numColumns" format="integer" />
        <attr name="hSpace" format="integer" />
        <attr name="vSpace" format="integer" />
    </declare-styleable>
</resources>

在程式中透過 TypedArray 讀取,並給好預設值:

public CustomGridView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    if (attrs != null) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.CustomGridView);
        colums = a.getInteger(R.styleable.CustomGridView_numColumns, 3);
        hSpace = a.getInteger(R.styleable.CustomGridView_hSpace, 10);
        vSpace = a.getInteger(R.styleable.CustomGridView_vSpace, 10);
        a.recycle();     // 記得回收
    }
}

public CustomGridView(Context context, AttributeSet attrs) { this(context, attrs, 0); }
public CustomGridView(Context context) { this(context, null); }

二、LayoutParams

LayoutParams 儲存子 View 加入容器時的參數資訊。自定義 ViewGroup 時,通常也要定義一個對應的 LayoutParams,做法與 SDK 中的 LinearLayout.LayoutParams、RelativeLayout.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); }
}

有了自訂的 LayoutParams,接著要覆寫四個工廠方法,讓 ViewGroup 在建立子 View 時採用我們的實作:

@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
    return new CustomGridLayout.LayoutParams(getContext(), attrs);
}

@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
    return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}

@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
    return new LayoutParams(p);
}

@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
    return p instanceof CustomGridLayout.LayoutParams;
}

三、onMeasure

onMeasure 要做兩件事:

1. 計算子 View 的測量值與模式

measureChildren(widthMeasureSpec, heightMeasureSpec);
measureChild(child, widthMeasureSpec, heightMeasureSpec);
child.measure(WidthMeasureSpec, HeightMeasureSpec);

2. 設定 ViewGroup 自己的寬高

若 layout_width / layout_height 是 match_parent 或具體 dp 值,直接 setMeasuredDimension() 即可;若是 wrap_content,就得遍歷所有子 View 完成測量,再依排列規則推算整體尺寸。

這裡也終於用上了上一篇提到的 UNSPECIFIED 模式——當父容器是 AdapterView 時,正是以這個模式呼叫 measure。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int widthMode  = MeasureSpec.getMode(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int sizeWidth  = MeasureSpec.getSize(widthMeasureSpec);
    int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);

    // UNSPECIFIED:父容器為 AdapterView 時透過 measure 傳入的模式
    final int childWidthMeasureSpec =
            MeasureSpec.makeMeasureSpec(sizeWidth, MeasureSpec.UNSPECIFIED);
    final int childHeightMeasureSpec =
            MeasureSpec.makeMeasureSpec(sizeHeight, MeasureSpec.UNSPECIFIED);
    measureChildren(childWidthMeasureSpec, childHeightMeasureSpec);

    int childCount = this.getChildCount();
    int line = childCount % colums == 0 ? childCount / colums : (childCount + colums) / colums;

    // 寬為 wrap_content 時取子 View 最大寬,否則依欄數均分
    if (widthMode == MeasureSpec.AT_MOST) {
        for (int i = 0; i < childCount; i++) {
            childWidth = Math.max(childWidth, getChildAt(i).getMeasuredWidth());
        }
    } else if (widthMode == MeasureSpec.EXACTLY) {
        childWidth = (sizeWidth - (colums - 1) * hSpace) / colums;
    }

    // 高同理
    if (heightMode == MeasureSpec.AT_MOST) {
        for (int i = 0; i < childCount; i++) {
            childHeight = Math.max(childHeight, getChildAt(i).getMeasuredHeight());
        }
    } else if (heightMode == MeasureSpec.EXACTLY) {
        childHeight = (sizeHeight - (line - 1) * vSpace) / line;
    }

    // 把每個子 View 的左上角座標存進 LayoutParams,留給 onLayout 使用
    for (int i = 0; i < childCount; i++) {
        LayoutParams lParams = (LayoutParams) getChildAt(i).getLayoutParams();
        lParams.left = (i % colums) * (childWidth + hSpace);
        lParams.top  = (i / colums) * (childHeight + vSpace);
    }

    // wrap_content 時推算整體尺寸
    int wrapWidth;
    if (childCount < colums) {
        wrapWidth = childCount * childWidth + (childCount - 1) * hSpace;
    } else {
        wrapWidth = colums * childWidth + (colums - 1) * hSpace;
    }
    int wrapHeight = line * childHeight + (line - 1) * vSpace;

    setMeasuredDimension(widthMode  == MeasureSpec.AT_MOST ? wrapWidth  : sizeWidth,
                         heightMode == MeasureSpec.AT_MOST ? wrapHeight : sizeHeight);
}

四、onLayout

核心就是依序呼叫每個子 View 的 layout(),座標直接取自測量階段算好的 LayoutParams:

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int childCount = this.getChildCount();
    for (int i = 0; i < childCount; i++) {
        View child = getChildAt(i);
        LayoutParams lParams = (LayoutParams) child.getLayoutParams();
        child.layout(lParams.left, lParams.top,
                     lParams.left + childWidth, lParams.top + childHeight);
    }
}

五、draw

ViewGroup 在 draw 階段,基本上就是依子 View 的排列順序去呼叫各自的 onDraw。因為容器本身通常不需要額外裝飾,所以往往不必覆寫 onDraw,沿用預設實作就好。

六、對外 API:Adapter 與點擊事件

為了讓外部能像使用 GridView 那樣餵資料,我們定義一個簡易的 adapter 介面:

public interface GridAdatper {
    View getView(int index);
    int getCount();
}

/** 設定檢視,並動態加入子 View */
public void setGridAdapter(GridAdatper adapter) {
    this.adapter = adapter;
    int size = adapter.getCount();
    for (int i = 0; i < size; i++) {
        addView(adapter.getView(i));
    }
}

再補上點擊回呼,讓外部能取得被點擊的項目:

public interface OnItemClickListener {
    void onItemClick(View v, int index);
}

public void setOnItemClickListener(final OnItemClickListener listener) {
    if (this.adapter == null) return;
    for (int i = 0; i < adapter.getCount(); i++) {
        final int index = i;
        getChildAt(i).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onItemClick(v, index);
            }
        });
    }
}

七、使用方式

版面配置:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res/com.hx.customgridview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#303030"
    android:orientation="vertical">

    <com.hx.customgridview.CustomGridLayout
        android:id="@+id/gridview"
        android:layout_width="200dp"
        android:layout_height="300dp"
        android:background="#1e1d1d"
        app:hSpace="10"
        app:vSpace="10"
        app:numColumns="3" />
</LinearLayout>

項目版面 grid_item:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY" />
</LinearLayout>

Activity 端:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    grid = (CustomGridLayout) findViewById(R.id.gridview);
    grid.setGridAdapter(new GridAdatper() {
        @Override
        public View getView(int index) {
            View view = getLayoutInflater().inflate(R.layout.grid_item, null);
            ImageView iv = (ImageView) view.findViewById(R.id.iv);
            iv.setImageResource(srcs[index]);
            return view;
        }
        @Override
        public int getCount() {
            return srcs.length;
        }
    });

    grid.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(View v, int index) {
            Toast.makeText(MainActivity.this, "item=" + index, Toast.LENGTH_SHORT).show();
        }
    });
}

固定寬高時的效果:

改成 wrap_content,容器會依內容自動縮放:

<com.hx.customgridview.CustomGridLayout
    android:id="@+id/gridview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#1e1d1d"
    app:hSpace="10" app:vSpace="10" app:numColumns="3" />

改成 match_parent,網格會撐滿並均分可用空間:

把欄數改成 4,排列隨之改變:

Demo 下載:https://xiazai.jb51.net/201609/yuanma/CustomGridLayout(jb51.net).rar

自定義 ViewGroup 的套路其實很固定:定義屬性 → 定義 LayoutParams 並覆寫工廠方法 → onMeasure 中先量子後量己 → onLayout 中依座標擺放。把這條主線記牢,後續要做瀑布流、流式版面或任何特殊排列,都只是換一套座標計算規則而已。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved