編輯:關於 Android 程式設計
在通訊錄、好友清單這類資料量龐大的列表中,使用者通常沒有耐心逐筆翻找。只要在畫面右側放上一條 A–Z 的字母索引,手指一滑便能跳到對應位置,操作體驗立刻截然不同。本文示範如何從零打造一個可自訂字型、可回報觸摸落點的自定義 View。
一個稱職的自定義 View,至少要滿足以下三個條件:
字母索引欄屬於單純的 View,因此核心工作落在 onDraw()。而針對 wrap_content,做法是在 onMeasure() 中給定一組預設寬高,防止 View 被拉伸成不合理的尺寸。
繪製之前必須掌握兩組資訊:每個字母的起始座標,以及字母本身的尺寸。成品還要滿足三個要求:水平居中、字型顏色可調、字型大小可調。
int paddingLeft = getPaddingLeft();
// view 實際可用寬度
int width = getWidth() - paddingLeft - getPaddingRight();
// 繪製字元的起始 x 座標
float startX = paddingLeft + (float) width / 2;
int paddingTop = getPaddingTop();
// view 實際可用高度
int height = getHeight() - paddingTop - getPaddingBottom();
int length = mCharacters.length();
// 每個字元平均可分到的高度
float characterHeight = (float) height / length;
// 繪製字元的起始 y 座標
float startY = paddingTop + characterHeight / 2;
// 用來量測字形的邊界
Rect bounds = new Rect();
mCharacterYValues = new int[length + 1];
for (int i = 0; i < length; i++) {
mPaint.getTextBounds(mCharacters, i, i + 1, bounds);
float x = startX - (float) (bounds.left + bounds.right) / 2;
float y = startY + i * characterHeight - (float) (bounds.top + bounds.bottom) / 2;
canvas.drawText(mCharacters, i, i + 1, x, y, mPaint);
// 記錄每個字元的起始 y 座標
mCharacterYValues[i] = (int) (paddingTop + i * characterHeight);
}
// 最後一個字元結束處的 y 座標
mCharacterYValues[length] = (int) (paddingTop + length * characterHeight);
整段邏輯可以拆成三個步驟:
int width = getWidth() - getPaddingLeft() - getPaddingRight();
int height = getHeight() - getPaddingTop() - getPaddingBottom();
Rect bounds = new Rect();
mPaint.getTextBounds(mCharacters, i, i + 1, bounds);
// 字寬 = bounds.left + bounds.right
// 字高 = bounds.top + bounds.bottom
之所以不能直接用 startX、startY 當作 drawText 的參數,是因為 drawText 給的是基線位置,而 getTextBounds 回傳的是相對於基線的上下左右偏移。/widgets 用這兩個偏移量做一次微調,字母才會真正落在格線中央。
float characterHeight = (float) height / mCharacters.length();
float startX = paddingLeft + (float) width / 2;
float startY = paddingTop + characterHeight / 2;
float x = startX - (float) (bounds.left + bounds.right) / 2;
float y = startY + i * characterHeight - (float) (bounds.top + bounds.bottom) / 2;
canvas.drawText(mCharacters, i, i + 1, x, y, mPaint);
對外暴露兩個回呼:手指按下時,以及手指滑過字母表時。
/**
* CharacterView 觸摸事件的監聽介面
*/
public interface OnCharacterTouchListener {
/**
* 點擊字元時回呼
*
* @param view CharacterView 本身
* @param c 被點擊的字元
*/
void onDown(View view, char c);
/**
* 在字母表上滑動時回呼
*
* @param view CharacterView 本身
* @param c 目前手指所在位置對應的字元
*/
void onMove(View view, char c);
}
核心思路很樸素:繪製時順手把每個字母的起始 y 座標存進陣列,觸摸發生時拿當前 y 座標去比對,落在哪個區間就是哪個字母。由於陣列本身已按座標遞增排序,正好可以套用二分搜尋。
/**
* 設定 CharacterView 的觸摸監聽器
*/
public void setOnCharacterTouchListener(final OnCharacterTouchListener listener) {
if (listener == null) {
setOnTouchListener(null);
return;
}
setOnTouchListener(new View.OnTouchListener() {
char lastCharacter = ' ';
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int yDown = (int) motionEvent.getY();
if (yDown > mCharacterYValues[0]
&& yDown < mCharacterYValues[mCharacterYValues.length - 1]) {
char c = findCharacter(yDown);
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
listener.onDown(view, c);
break;
case MotionEvent.ACTION_MOVE:
// 只有跨過字母分界線時才回呼,避免同一字母被連續觸發
if (lastCharacter == ' ' || lastCharacter != c) {
listener.onMove(view, c);
lastCharacter = c;
}
break;
case MotionEvent.ACTION_UP:
break;
}
}
return true;
}
});
}
/**
* 依 y 座標找出對應的字元
*/
private char findCharacter(int yValue) {
int low = 0, high = mCharacterYValues.length - 1;
int lastMid = 0;
while (low <= high) {
int mid = (low + high) / 2;
lastMid = mid;
if (mCharacterYValues[mid] == yValue) {
return mCharacters.charAt(mid);
} else if (mCharacterYValues[mid] < yValue) {
low = mid + 1;
} else {
high = mid - 1;
}
}
int closestPointIndex = lastMid;
// 若最後一次比較結果大於目標值,需回退一個下標
if (mCharacterYValues[lastMid] > yValue) {
closestPointIndex -= 1;
}
return mCharacters.charAt(closestPointIndex);
}
以 A、B、C …… 一直到 Z 為例,繪製時記錄下 A 之前的邊界到 Z 之後的邊界,總共 length + 1 個切點;查找時只要判斷 y 座標落在哪一段區間即可。
// 每個字元的起始 y 座標
mCharacterYValues[i] = (int) (paddingTop + i * characterHeight);
// 最後一個字元結束處的 y 座標
mCharacterYValues[length] = (int) (paddingTop + length * characterHeight);
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthSpecMode == MeasureSpec.AT_MOST) {
final int defaultWidth = 80;
setMeasuredDimension(defaultWidth, heightSpecSize);
}
}
高度刻意不設預設值,因為當 layout_height 寫成 wrap_content 時,直接讓它對齊父容器的高度反而更合用。
版面配置 activity_main.xml:
<FrameLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.wj.study.MainActivity">
<com.wj.study.view.CharacterView
android:id="@+id/character_view"
android:layout_width="@dimen/size_35dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginRight="5dp"
android:padding="5dp" />
</FrameLayout>
MainActivity:
package com.wj.study;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.wj.study.view.CharacterView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CharacterView characterView = (CharacterView) findViewById(R.id.character_view);
characterView.insertFirst('#');
characterView.setBackgroundColor(Color.CYAN);
characterView.setColor(Color.BLUE);
characterView.setTextSize(getResources().getDimensionPixelSize(R.dimen.textSize_14sp));
characterView.setOnCharacterTouchListener(new CharacterView.OnCharacterTouchListener() {
@Override
public void onDown(View view, char c) {
Log.d("TAG", "onDown=" + c);
}
@Override
public void onMove(View view, char c) {
Log.d("TAG", "onMove=" + c);
Toast.makeText(view.getContext(), String.valueOf(c), Toast.LENGTH_SHORT).show();
}
});
}
}
CharacterView:
package com.wj.study.view;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* CharacterView 依名稱首字母提供快速定位能力,
* 常見於通訊錄、好友列表等場景。
*/
public class CharacterView extends View {
private String mCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
private int[] mCharacterYValues = null;
public CharacterView(Context context) {
super(context);
}
public CharacterView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CharacterView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(21)
public CharacterView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthSpecMode == MeasureSpec.AT_MOST) {
final int defaultWidth = 80;
setMeasuredDimension(defaultWidth, heightSpecSize);
}
}
@Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(2.0f);
int paddingLeft = getPaddingLeft();
int width = getWidth() - paddingLeft - getPaddingRight();
float startX = paddingLeft + (float) width / 2;
int paddingTop = getPaddingTop();
int height = getHeight() - paddingTop - getPaddingBottom();
int length = mCharacters.length();
float characterHeight = (float) height / length;
float startY = paddingTop + characterHeight / 2;
Rect bounds = new Rect();
mCharacterYValues = new int[length + 1];
for (int i = 0; i < length; i++) {
mPaint.getTextBounds(mCharacters, i, i + 1, bounds);
float x = startX - (float) (bounds.left + bounds.right) / 2;
float y = startY + i * characterHeight - (float) (bounds.top + bounds.bottom) / 2;
canvas.drawText(mCharacters, i, i + 1, x, y, mPaint);
mCharacterYValues[i] = (int) (paddingTop + i * characterHeight);
}
mCharacterYValues[length] = (int) (paddingTop + length * characterHeight);
}
/** 設定字型大小 */
public void setTextSize(float textSize) {
mPaint.setTextSize(textSize);
}
/** 設定畫筆顏色 */
public void setColor(int color) {
mPaint.setColor(color);
}
/** 在字母表最前面插入一個字元 */
public void insertFirst(char c) {
StringBuilder sb = new StringBuilder();
sb.append(c).append(mCharacters);
mCharacters = sb.toString();
}
/** 在字母表最後面插入一個字元 */
public void insertLast(char c) {
StringBuilder sb = new StringBuilder();
sb.append(mCharacters).append(c);
mCharacters = sb.toString();
}
/** 自訂字母表 */
public void setCharacter(String characters) {
if (characters == null) {
return;
}
mCharacters = characters;
}
/** 設定觸摸監聽器 */
public void setOnCharacterTouchListener(final OnCharacterTouchListener listener) {
if (listener == null) {
setOnTouchListener(null);
return;
}
setOnTouchListener(new View.OnTouchListener() {
char lastCharacter = ' ';
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int yDown = (int) motionEvent.getY();
if (yDown > mCharacterYValues[0]
&& yDown < mCharacterYValues[mCharacterYValues.length - 1]) {
char c = findCharacter(yDown);
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
listener.onDown(view, c);
break;
case MotionEvent.ACTION_MOVE:
if (lastCharacter == ' ' || lastCharacter != c) {
listener.onMove(view, c);
lastCharacter = c;
}
break;
case MotionEvent.ACTION_UP:
break;
}
}
return true;
}
});
}
/** 依 y 座標找出對應字元 */
private char findCharacter(int yValue) {
int low = 0, high = mCharacterYValues.length - 1;
int lastMid = 0;
while (low <= high) {
int mid = (low + high) / 2;
lastMid = mid;
if (mCharacterYValues[mid] == yValue) {
return mCharacters.charAt(mid);
} else if (mCharacterYValues[mid] < yValue) {
low = mid + 1;
} else {
high = mid - 1;
}
}
int closestPointIndex = lastMid;
if (mCharacterYValues[lastMid] > yValue) {
closestPointIndex -= 1;
}
return mCharacters.charAt(closestPointIndex);
}
/** 觸摸事件回呼介面 */
public interface OnCharacterTouchListener {
void onDown(View view, char c);
void onMove(View view, char c);
}
}
字母索引欄只是半個功能,另一半是清單跟著定位。至於如何把它與 ListView 或 RecyclerView 聯動起來,留待下一篇討論。
Android 自定義 View 高級特效:神奇的貝塞爾曲線
效果預覽 效果圖中我們實現了一個隨手指滑動變化的二階貝塞爾曲線,還有一個能穿越所有已知點的複雜貝塞爾曲線。學會使用貝塞爾曲線後,可以做出 QQ 紅點滑動刪除、360 動
Android 核心層與檔案系統層 printf 輸出原理剖析
從 /dev/console 看輸出起點 在 Android 或 Linux 系統中,/dev/console 是與系統互動的控制台設備,也是 TTY 設備的一種。使用者
Android 學習筆記(四):Activity 全景解析——生命週期、通信、啟動模式與系統調用
一、Activity 是什麼 Activity 是 Android 四大組件之一,用於承載 View、提供用戶交互入口。它本身並不繪製界面,而是創建一個窗口,在其上進行繪
Android 圖片特效實作:黑白、圓角與高斯模糊
在 Android 中對圖片做特效處理是很實用的技巧。本文整理三種常見效果的實作:黑白化、圓角與高斯模糊。 一、黑白效果 將彩色圖轉為黑白圖的核心,是把每個像素的 RG