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

下面給兩條路:一條是重寫 dispatchDraw 用 Canvas 手畫,另一條是更省事也更穩的做法——給每個 item 一個「自帶邊框」的背景。
思路是遍歷所有可見子 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 的背景自帶一圈描邊。這樣分割線的問題就變成了「寫一個 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>
<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>
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 背景會省心得多,也不用糾結「最後一行少畫了一條線」。
ListView 多類型 Item 實現方案與 RecycleBin 回收機制源碼剖析
一、概述 一般情況下,ListView 的每個 item 樣式都相同,但實際場景中不同位置的 item 需要不同樣式的需求非常多。 以微信為例:早期版本的代表作是消息列表
項目源碼分享:Android「美女的秘密」圖片瀏覽應用
項目源碼分享:Android「美女的秘密」圖片瀏覽應用 這是一個結構輕量的 Android 圖片瀏覽類項目,代碼量不大,適合初學者拿來練習列表加圖片加載的組合套路。 源
手機衛士實戰:自定義可獲焦點的跑馬燈 TextView
打造始終獲焦的跑馬燈文字效果 本文將實現標題欄下方 TextView 的文字跑馬燈效果,讓一行文字水平循環滾動。先看效果: 一、直接用系統 TextView 實現
Android 文字漸變與歌詞進度效果實現
文字漸變效果Android 可透過 LinearGradient 為文字加上線性漸變,也能利用自定義 View 或 ProgressBar 做出歌詞進度效果。Linear