編輯:關於 Android 開發
在 Android 開發中,divider(兩個 View 之間的分割線)幾乎無處不在。最近工作時我特別留意了這個看似不起眼的小元素,深入研究後才發現裡頭大有學問。以下從 ListView、RecyclerView 到自定義分割線,逐一拆解。
ListView 的 divider 預設是左右貫穿的,若想加上邊距,用 inset 或 layer-list 都能輕鬆搞定:
<!-- 方法一 -->
<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="https://schemas.android.com/apk/res/android"
android:insetLeft="16dp" >
<shape android:shape="rectangle" >
<solid android:color="#f00" />
</shape>
</inset>
<!-- 方法二 -->
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="https://schemas.android.com/apk/res/android">
<item android:left="16dp">
<shape android:shape="rectangle">
<solid android:color="#f00" />
</shape>
</item>
</layer-list>
其中 inset 除了 insetLeft,還有 insetTop、insetRight、insetBottom,四個方向都能自訂。

很多人發現,ListView 最後一項的 divider 時有時無。原因在於 ListView 計算高度時並不把最後一項的 divider 算進去,因此只有在 match_parent、高度還有餘裕時,最後那條線才畫得出來。下圖說明得很清楚:

補充一個常見誤區:網路上不少資料把最後一項的 divider 與 footerDividersEnabled 混為一談,這其實是不對的。兩者在邏輯上彼此獨立,headerDividersEnabled 也是同理,它們只專供 header 與 footer 使用,並不影響預設的最後一條分割線繪製。
RecyclerView 的分割線叫做 ItemDecoration,它是個抽象類別,官方並未提供預設實作。官方 Support7Demos 範例裡有個 DividerItemDecoration 可供參考,位於 sdk 的:
extras/android/support/samples/Support7Demos/src/…/…/decorator/DividerItemDecoration.java
但這個官方範例存在幾個問題。為此我做了修復與增強:預設採用系統分割線、支援自定義 Drawable、同時支援水平與垂直方向,並修正了官方垂直 Divider 顯示上的 bug。核心程式碼如下:
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
private static final int[] ATTRS = new int[]{ android.R.attr.listDivider };
public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
private Drawable mDivider;
private int mWidth;
private int mHeight;
private int mOrientation;
public DividerItemDecoration(Context context, int orientation) {
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
setOrientation(orientation);
}
// 新增:支援自定義 dividerDrawable
public DividerItemDecoration(Context context, int orientation, Drawable dividerDrawable) {
mDivider = dividerDrawable;
setOrientation(orientation);
}
public void setOrientation(int orientation) {
if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
throw new IllegalArgumentException("invalid orientation");
}
mOrientation = orientation;
}
public void setWidth(int width) { this.mWidth = width; }
public void setHeight(int height) { this.mHeight = height; }
@Override public void onDraw(Canvas c, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) { drawVertical(c, parent); }
else { drawHorizontal(c, parent); }
}
public void drawVertical(Canvas c, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin + Math.round(ViewCompat.getTranslationY(child));
final int bottom = top + getDividerHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
public void drawHorizontal(Canvas c, RecyclerView parent) {
final int top = parent.getPaddingTop();
final int bottom = parent.getHeight() - parent.getPaddingBottom();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
final int left = child.getRight() + params.rightMargin + Math.round(ViewCompat.getTranslationX(child));
final int right = left + getDividerWidth();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
@Override public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) { outRect.set(0, 0, 0, getDividerHeight()); }
else { outRect.set(0, 0, getDividerWidth(), 0); }
}
private int getDividerWidth() { return mWidth > 0 ? mWidth : mDivider.getIntrinsicWidth(); }
private int getDividerHeight() { return mHeight > 0 ? mHeight : mDivider.getIntrinsicHeight(); }
}
使用方式相當彈性,無論系統預設線、圖片 Drawable 還是純色線都能勝任:
// 預設系統的 divider
dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST);
// 自定義圖片 drawable 的 divider
dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST, getResources().getDrawable(R.drawable.ic_launcher));
// 自定義無寬高的 drawable - 垂直列表
dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST, new ColorDrawable(Color.parseColor("#ff00ff")));
dividerItemDecoration.setHeight(1);
// 自定義無寬高的 drawable - 水平列表
dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL_LIST, new ColorDrawable(Color.parseColor("#ff00ff")));
dividerItemDecoration.setWidth(1);
有些時候沒有系統控件的原生支援,只能手動在兩個 View 之間塞一個分割線。橫的豎的都難不倒人,定義一個 View 加上背景色即可。真正值得探討的是常見的「設置頁」——分割線帶有左邊距,例如微信風格的設定畫面。多數人的寫法如下:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- group_container 的背景必須設置,且要與 list_item_normal 一致,否則效果會不正確 -->
<LinearLayout android:id="@+id/group_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="48dp"
android:background="#fff"
android:orientation="vertical">
<RelativeLayout android:id="@+id/account_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/list_item_bg"
android:clickable="true">
<TextView android:id="@+id/account_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_margin="16dp"
android:text="First Item"
android:textColor="#f00"
android:textSize="16sp" />
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="1px"
android:layout_marginLeft="16dp"
android:background="#f00" />
</LinearLayout>
</RelativeLayout>
用 Overdraw 工具分析後會發現:只為了一條分割線的左邊距,卻替整個 group_container 設了背景,白白多了一次 Overdraw。

能否優化掉這次 Overdraw?當然可以。做法是拿掉背景,並自定義一個 SpaceDividerView,讓它把空出的 16dp 用 list_item_normal 的顏色補畫出來,這樣左邊距的視覺效果就能保留:
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import com.jayfeng.lesscode.core.R;
public class SpaceDividerView extends View {
private int mSpaceLeft = 0, mSpaceTop = 0, mSpaceRight = 0, mSpaceBottom = 0;
private int mSpaceColor = Color.TRANSPARENT;
private Paint mPaint = new Paint();
public SpaceDividerView(Context context) { this(context, null); }
public SpaceDividerView(Context context, AttributeSet attrs) { this(context, attrs, 0); }
public SpaceDividerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SpaceDividerView, defStyleAttr, 0);
mSpaceLeft = a.getDimensionPixelSize(R.styleable.SpaceDividerView_spaceLeft, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0, getResources().getDisplayMetrics()));
mSpaceTop = a.getDimensionPixelSize(R.styleable.SpaceDividerView_spaceTop, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0, getResources().getDisplayMetrics()));
mSpaceRight = a.getDimensionPixelSize(R.styleable.SpaceDividerView_spaceRight, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0, getResources().getDisplayMetrics()));
mSpaceBottom = a.getDimensionPixelSize(R.styleable.SpaceDividerView_spaceBottom, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0, getResources().getDisplayMetrics()));
mSpaceColor = a.getColor(R.styleable.SpaceDividerView_spaceColor, Color.TRANSPARENT);
a.recycle();
mPaint.setColor(mSpaceColor);
}
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mSpaceLeft > 0) { canvas.drawRect(0, 0, mSpaceLeft, getMeasuredHeight(), mPaint); }
if (mSpaceTop > 0) { canvas.drawRect(0, 0, getMeasuredWidth(), mSpaceTop, mPaint); }
if (mSpaceRight > 0) { canvas.drawRect(getMeasuredWidth() - mSpaceRight, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint); }
if (mSpaceBottom > 0) { canvas.drawRect(0, getMeasuredHeight() - mSpaceBottom, getMeasuredWidth(), getMeasuredHeight(), mPaint); }
}
}
用它重寫後的佈局,把背景拿掉、改用 spaceLeft 與 spaceColor 屬性即可:
<com.jayfeng.lesscode.core.other.SpaceDividerView
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#f00"
app:spaceLeft="16dp"
app:spaceColor="@color/list_item_normal"/>
優化後 group_container 那塊由綠色變成藍色,代表成功減少了一次 Overdraw。SpaceDividerView 解耦了背景色、支援四個方向,實用性相當高。

陰影分割線的特點是重疊在下方 View 之上,營造立體的層次感。實作上只要用 RelativeLayout 並控制好上邊距即可,關鍵是 header 要放在最後才能顯示在最上層:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- layout_marginTop 的值應為不含陰影高度的 header 高度 -->
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_marginTop="@dimen/header_height"
android:orientation="vertical">
</LinearLayout>
<!-- 放在最後才能顯示在最上層,header 內含一個陰影 View -->
<include android:id="@+id/header" layout="@layout/include_header" />
</RelativeLayout>
原理很簡單:header 包含內容 48dp 與陰影 8dp,那麼 marginTop 就設為 48dp 即可。

Android 圖片自動輪播實作:Timer 搭配 Handler 的節奏控制
需求與思路 要做一個自動輪播的圖片展示區,關鍵在「定時」與「換圖」兩件事分開處理:用 Timer 負責計時,用 Handler 負責把換圖的訊息送回主執行緒更新畫面。這樣
深入解析 Android Touch 事件分發機制
深入解析 Android Touch 事件分發機制 在 Touch 事件分發的體系裡,其實只有兩個主角:ViewGroup 與 View。Activity 的 Touch
lesson3:Qt 對話框完全指南——QDialog 與六大內建對話框
一、QDialog 類別 1. 對話框的概念 對話框在各式軟體中無所不在,主要用來向使用者提示資訊或接收使用者回饋,是應用程式與使用者互動的橋樑。 對話框是一個頂層視窗,
AndroidAnnotations 標註詳解:Injection 注入標籤全攻略(十)
一文讀懂常用注入標註 前面我們講過 AndroidAnnotations 的元件注入方式,本篇系統整理 Injection 相關標註的用法,方便日後查閱。 @AfterE