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

給 Android GridView 畫上分割線:兩種思路的完整實現

編輯:關於 Android 開發

給 GridView 畫分割線

ListView 想加分割線很簡單,布局裡寫上 android:divider 和 android:dividerHeight 就完事。可 GridView 偏偏沒有這兩個屬性,於是「九宮格加細線」就成了不少人的小難題——比如支付寶錢包首頁那種帶格線的功能入口。

下面給兩條路:一條是重寫 dispatchDraw 用 Canvas 手畫,另一條是更省事也更穩的做法——給每個 item 一個「自帶邊框」的背景。

方案一:自定義 LineGridView,在 dispatchDraw 裡畫線

思路是遍歷所有可見子 View,根據列數判斷每個格子該補哪幾條邊:第一行補上邊、第一列補左邊、每列末尾補右邊、非最後一行補下邊。

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);

        View firstChild = getChildAt(0);
        if (firstChild == null) {
            return;
        }
        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 個數不能被列數整除時就容易漏線或多線,實際跑起來常常「有些格子沒有分割線」。想做得漂亮,得把算法再打磨一輪。

配套使用代碼

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();
        }
    }
}

布局文件

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

    <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.LineGridView
        android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv"
        android:layout_margin="10dp"
        android:background="#ffffff"
        android:gravity="center"
        android:listSelector="@null"
        android:numColumns="3"
        android:padding="3dp"
        android:stretchMode="columnWidth" />

</RelativeLayout>
<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="@color/item_select"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="全部" />

</LinearLayout>

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

真正省事的做法是:別去畫線,而是讓每個 item 的背景自帶一圈描邊。這樣分割線的問題就變成了「寫一個 selector」的問題,與列數、行數、整除關係全部無關。

第一步:寫帶描邊的 selector

用一組 <item> 定義不同狀態:外層用矩形 rectangle,把 stroke 的顏色設成分割線顏色,再按 state 疊上不同的 gradient,這樣被點選時的高亮效果也順帶有了。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <stroke android:width="1px" android:color="@color/line" />
            <gradient android:startColor="#EEEEEE" android:endColor="#DDDDDD" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <stroke android:width="1px" android:color="@color/line" />
            <gradient android:startColor="#FFFFFF" android:endColor="#FFFFFF" />
        </shape>
    </item>
</selector>

第二步:把背景掛到 item 布局上

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_margin="0.0dip"
    android:background="@color/griditems_bg">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true"
        android:background="@drawable/bg_gv"
        android:padding="12.0dip">

        <ImageView
            android:id="@+id/iv_item"
            android:layout_width="58.0dip"
            android:layout_height="58.0dip"
            android:layout_centerHorizontal="true"
            android:contentDescription="@string/app_name" />

        <TextView
            android:id="@+id/tv_item"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/iv_item"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="5.0dip"
            android:maxLines="1"
            android:textColor="@color/commo_text_color"
            android:textSize="14.0sp" />

    </RelativeLayout>

</LinearLayout>

順帶解決一個老熟人:GridView 嵌在 ScrollView 裡只顯示一行

item 比較多時,我們習慣用 ScrollView 把 GridView 包起來。結果就是那個經典坑:只顯示第一行,後面的數據全不見了。原因大致是 GridView 本身要根據子 item 自適應高度,而一旦放進可滑動的 ScrollView,系統就猶豫了「到底該畫多高」。

解法是重寫 onMeasure,把高度規格改成不超過一個極大值,讓 GridView 自己按內容撐開:

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
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(
                Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}

剩下的事情就只是寫一個 Adapter 把數據填進 GridView,這一步大家都熟。

兩種方案怎麼選

如果你的格子有固定形狀、需要在畫布層面控制線的粗細或顏色,走 dispatchDraw 更靈活;如果只是想要一張整齊的九宮格,用帶描邊的 selector 背景會省心得多,也不用糾結「最後一行少畫了一條線」。

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