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

思路是攔截繪製流程,遍歷可見子 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 較多時通常會用 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);
}
}
用 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>
<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>
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 布局。
把 Android 開源庫發佈到 JCenter:流程、配置與常見坑
前言 越來越多 Android 開發者會把自己的成果整理成開源庫。透過 JCenter 發佈後,其他人只需要在 gradle 中加入一行依賴,就能快速使用。本文整理從建立
Android 開發中 ContentProvider 的使用詳解
前言 ContentProvider 為存儲數據和獲取數據提供了統一的接口,能夠實現不同應用程序之間的數據共享。與上一篇介紹的 SQLite 只能在同一個應用內共享數據不
Android 學習教程(4):圖片毛玻璃效果實作
本文分享毛玻璃(高斯模糊)效果的完整實作,同時支援本地圖片與網路圖片兩種來源,模糊程度可透過輸入框即時調整。 BlurimageActivity.java packa
Android 通知(Notification)詳解:從發送到點擊跳轉
最近專案裡用到了 Android 的通知機制,趁機會透過一個完整範例把整個流程走一遍。 發送一則通知其實很簡單 核心只有三件事:建立 PendingIntent 決定點