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

GridView 實現帶分割線的九宮格:兩種方案對比

編輯:關於 Android 程式設計

ListView 想加分割線很簡單,布局裡寫 android:divider 和 android:dividerHeight 就行。GridView 沒有這兩個屬性,需要自己想辦法。本文對比兩種常見做法。

方案一:自定義 GridView 在 dispatchDraw 中畫線

思路是攔截繪製流程,遍歷可見子 View,用 Canvas 逐條畫出橫豎線。核心代碼:

public class LineGridView extends GridView {

    public LineGridView(Context context) { super(context); }
    public LineGridView(Context context, AttributeSet attrs) { super(context, attrs); }
    public LineGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);

        if (getChildCount() == 0) return;

        View firstChild = getChildAt(0);
        int column = getWidth() / firstChild.getWidth();  // 列数
        int childCount = getChildCount();

        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(getContext().getResources().getColor(R.color.line));

        for (int i = 0; i < childCount; i++) {
            View cell = getChildAt(i);

            if (i < column) {   // 第一行顶部横线
                canvas.drawLine(cell.getLeft(), cell.getTop(),
                        cell.getRight(), cell.getTop(), paint);
            }
            if (i % column == 0) {   // 第一列左侧竖线
                canvas.drawLine(cell.getLeft(), cell.getTop(),
                        cell.getLeft(), cell.getBottom(), paint);
            }
            if ((i + 1) % column == 0) {   // 每行最后一列
                canvas.drawLine(cell.getLeft(), cell.getBottom(),
                        cell.getRight(), cell.getBottom(), paint);
                canvas.drawLine(cell.getRight(), cell.getTop(),
                        cell.getRight(), cell.getBottom(), paint);
            } else if ((i + 1) > (childCount - (childCount % column))) {
                // 最后一行:右竖线 + 底横线
                canvas.drawLine(cell.getRight(), cell.getTop(),
                        cell.getRight(), cell.getBottom(), paint);
                canvas.drawLine(cell.getLeft(), cell.getBottom(),
                        cell.getRight(), cell.getBottom(), paint);
            } else {
                canvas.drawLine(cell.getRight(), cell.getTop(),
                        cell.getRight(), cell.getBottom(), paint);
                canvas.drawLine(cell.getLeft(), cell.getBottom(),
                        cell.getRight(), cell.getBottom(), paint);
            }
        }
    }
}

這個方案的問題:依賴大量邊界判斷(首行、首列、末列、末行、行數不能整除),一旦列數或數據個數變化就容易出現漏線、多線。實際測試中,某些 item 邊緣就是畫不上分割線,很難達到預期效果。列數也被硬編碼邏輯綁住,複用性較差。

方案二:給每個 item 設置帶描邊的背景(推薦)

據說這是支付寶錢包首頁九宮格的實現思路。原理很樸素:不去畫線,而是讓每個 item 自帶邊框,線自然就出來了。

1. 處理 ScrollView 嵌套 GridView 只顯示一行的問題

item 較多時通常會用 ScrollView 包裹 GridView,但這會導致只顯示第一行數據。原因是 ListView/GridView 自身可根據子項計算高度,而放進可滑動容器後系統無法確定該給多大。做法是重寫 onMeasure:

public class MyGridView extends GridView {

    public MyGridView(Context context) { super(context); }
    public MyGridView(Context context, AttributeSet attrs) { super(context, attrs); }
    public MyGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(
                Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}

2. 定義帶描邊的 selector 背景

用 shape 定義矩形,stroke 就是分割線,gradient 負責不同狀態下的填充色:

<!-- bg_gv.xml -->
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <stroke android:width="1dp" android:color="@color/line" />
            <solid android:color="@color/item_select" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <stroke android:width="1dp" android:color="@color/line" />
            <solid android:color="@color/white" />
        </shape>
    </item>
</selector>

3. 布局

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

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="@string/hello_world" />

    <com.zdy.bbs_bbb.clicktoast.MyGridView
        android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv"
        android:background="#ffffff"
        android:gravity="center"
        android:listSelector="@null"
        android:numColumns="3"
        android:padding="3dp"
        android:stretchMode="columnWidth" />
</LinearLayout>

item 布局的根容器把背景設為該 selector:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/ll"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_gv"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv_item"
        android:layout_width="58dp"
        android:layout_height="58dp"
        android:layout_centerHorizontal="true"
        android:contentDescription="@string/app_name"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/tv_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:maxLines="1"
        android:text="全部"
        android:textColor="@color/commo_text_color"
        android:textSize="14sp" />
</LinearLayout>

4. Adapter 與 Activity

public class Main2Activity extends Activity {

    private LineGridView gridview;

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

        gridview = (LineGridView) findViewById(R.id.gridview);
        findViewById(R.id.tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { finish(); }
        });

        final MyAdapter adapter = new MyAdapter();
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adapter.setSelectItem(position);
            }
        });
        gridview.setAdapter(adapter);
    }

    private class MyAdapter extends BaseAdapter {
        private int currentItem = 0;

        @Override public int getCount() { return 5; }
        @Override public Object getItem(int position) { return null; }
        @Override public long getItemId(int position) { return 0; }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = View.inflate(Main2Activity.this, R.layout.gride_list_item, null);
            LinearLayout ll = (LinearLayout) v.findViewById(R.id.ll);
            if (position == currentItem) {
                ll.setBackgroundColor(getResources().getColor(R.color.item_select));
            } else {
                ll.setBackgroundColor(getResources().getColor(R.color.white));
            }
            return v;
        }

        public void setSelectItem(int position) {
            currentItem = position;
            notifyDataSetChanged();
        }
    }
}

兩種方案怎麼選

方案一依賴繪製計算,邊界條件多、容易出錯,列數變化時維護成本高。方案二把分割線交給背景,代碼極簡,item 之間的線自然拼接,也不受列數影響,是更值得採用的做法。

如果追求更好的性能,getView 中應複用 convertView 並使用 ViewHolder 模式,避免每次滑動都重新 inflate 布局。

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