編輯:關於 Android 程式設計
前陣子群裡有位同學的專案需要一個「雙端範圍選擇器」,看著對方受苦受難,實在于心不忍。正當我在「事不關己」與「拔刀相助」之間糾結時,一句「沒事多造點輪子,你的人生會有很多收穫」把我說服了。於是就有了這篇。


當可拖拽的範圍極限為零時——也就是 RangeSeekBar 仍能正常顯示的臨界狀態——粗略判斷是:寬度需大於 2 倍高度。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (heightSize * 2 > widthSize) {
setMeasuredDimension(widthSize, widthSize / 2);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public class RangeSeekBar extends View {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private int lineTop, lineBottom, lineLeft, lineRight;
private int lineCorners;
private int lineWidth;
private RectF line = new RectF();
public RangeSeekBar(Context context) {
this(context, null);
}
public RangeSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (heightSize * 2 > widthSize) {
setMeasuredDimension(widthSize, (int) (widthSize / 2));
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
int seekBarRadius = h / 2;
/**
* left / right / top / bottom 描述 SeekBar 按鈕的位置,
* 依此預先算出背景條 RectF 的四邊。
* 圓潤的轉角通常比直角好看。
*/
lineLeft = seekBarRadius;
lineRight = w - seekBarRadius;
lineTop = seekBarRadius - seekBarRadius / 4;
lineBottom = seekBarRadius + seekBarRadius / 4;
lineWidth = lineRight - lineLeft;
line.set(lineLeft, lineTop, lineRight, lineBottom);
lineCorners = (int) ((lineBottom - lineTop) * 0.45f);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setStyle(Paint.Style.FILL);
paint.setColor(0xFFD7D7D7);
canvas.drawRoundRect(line, lineCorners, lineCorners, paint);
}
}
這裡把 seekBarRadius 定為 SeekBar 按鈕的半徑,也就是 RangeSeekBar 高度的一半。既然預設狀態下按鈕圓心要正好壓在背景條的起點與終點,那麼背景條的起點和終點自然要各自往內縮一個半徑。

拖動舞台備好、按鈕半徑也定了,接下來就是畫按鈕。
仔細想想,按鈕有顏色、有大小、有變色、要被繪製、要做碰撞與邊界檢測、要被拖拽,而且還不只一個——實在是個複雜的集合體,是时候抽成物件了。
private class SeekBar {
int widthSize;
int left, right, top, bottom;
Bitmap bmp;
/**
* RangeSeekBar 尺寸變化時,按鈕尺寸隨之變化
*
* @param centerX 按鈕 X 中心在 RangeSeekBar 中的相對位置
* @param centerY 按鈕 Y 中心在 RangeSeekBar 中的相對位置
* @param heightSize RangeSeekBar 期望按鈕擁有的高度
*/
void onSizeChanged(int centerX, int centerY, int heightSize) {
/**
* left / right / top / bottom 描述按鈕佔用的矩形區域。
* widthSize 取高度的 0.8 倍,所以按鈕實際佔的是矩形而非正方形——
* 原因是圓形按鈕需要留出陰影空間。
*/
widthSize = (int) (heightSize * 0.8f);
left = centerX - widthSize / 2;
right = centerX + widthSize / 2;
top = centerY - heightSize / 2;
bottom = centerY + heightSize / 2;
bmp = Bitmap.createBitmap(widthSize, heightSize, Bitmap.Config.ARGB_8888);
int bmpCenterX = bmp.getWidth() / 2;
int bmpCenterY = bmp.getHeight() / 2;
int bmpRadius = (int) (widthSize * 0.5f);
Canvas defaultCanvas = new Canvas(bmp);
Paint defaultPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
// 繪製陰影
defaultPaint.setStyle(Paint.Style.FILL);
int barShadowRadius = (int) (bmpRadius * 0.95f);
defaultCanvas.save();
defaultCanvas.translate(0, bmpRadius * 0.25f);
RadialGradient shadowGradient = new RadialGradient(bmpCenterX, bmpCenterY,
barShadowRadius, Color.BLACK, Color.TRANSPARENT, Shader.TileMode.CLAMP);
defaultPaint.setShader(shadowGradient);
defaultCanvas.drawCircle(bmpCenterX, bmpCenterY, barShadowRadius, defaultPaint);
defaultPaint.setShader(null);
defaultCanvas.restore();
// 繪製按鈕本體
defaultPaint.setStyle(Paint.Style.FILL);
defaultPaint.setColor(0xFFFFFFFF);
defaultCanvas.drawCircle(bmpCenterX, bmpCenterY, bmpRadius, defaultPaint);
// 繪製邊框
defaultPaint.setStyle(Paint.Style.STROKE);
defaultPaint.setColor(0xFFD7D7D7);
defaultCanvas.drawCircle(bmpCenterX, bmpCenterY, bmpRadius, defaultPaint);
}
void draw(Canvas canvas) {
canvas.drawBitmap(bmp, left, top, null);
}
}
接著在 RangeSeekBar 中把它掛起來:
public class RangeSeekBar extends View {
private SeekBar seekBar = new SeekBar();
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
int seekBarRadius = h / 2;
// ...其餘計算省略
// 尺寸確定時,同步確定按鈕尺寸
seekBar.onSizeChanged(seekBarRadius, seekBarRadius, h);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// ...軌道繪製省略
// 繪製按鈕
seekBar.draw(canvas);
}
}
距離成功又近了一步。

@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
boolean touchResult = false;
// 判斷手指是否落在按鈕佔用的矩形區域內
if (seekBar.collide(event)) {
touchResult = true;
}
return touchResult;
case MotionEvent.ACTION_MOVE:
float percent;
float x = event.getX();
if (x <= lineLeft) {
percent = 0;
} else if (x >= lineRight) {
percent = 1;
} else {
percent = (x - lineLeft) * 1f / lineWidth;
}
// 按鈕依手指在軌道上的位置滑動
seekBar.slide(percent);
invalidate();
break;
}
return super.onTouchEvent(event);
}
private class SeekBar {
int lineWidth; // 軌道寬度,可在 onSizeChanged 時取得
float currPercent;
int left, right, top, bottom;
boolean collide(MotionEvent event) {
float x = event.getX();
float y = event.getY();
int offset = (int) (lineWidth * currPercent);
return x > left + offset && x < right + offset && y > top && y < bottom;
}
void slide(float percent) {
if (percent < 0) percent = 0;
else if (percent > 1) percent = 1;
currPercent = percent;
}
void draw(Canvas canvas) {
int offset = (int) (lineWidth * currPercent);
canvas.save();
canvas.translate(offset, 0);
canvas.drawBitmap(bmp, left, top, null);
canvas.restore();
}
}

目前為止,按鈕被按壓時顯得死氣沉沉。既然 UI 需要隨觸摸狀態變化,那麼先前在 onSizeChanged 裡預先生成圖案的偷懶做法就行不通了。先在 onTouchEvent 中捕捉這個變化:
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
seekBar.material = seekBar.material >= 1 ? 1 : seekBar.material + 0.1f;
// ...
invalidate();
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
seekBar.materialRestore();
break;
}
return super.onTouchEvent(event);
}
然後在按鈕內部回應這個狀態:
private class SeekBar {
float material = 0;
ValueAnimator anim;
final TypeEvaluator<Integer> te = new TypeEvaluator<Integer>() {
@Override
public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
int alpha = (int) (Color.alpha(startValue)
+ fraction * (Color.alpha(endValue) - Color.alpha(startValue)));
int red = (int) (Color.red(startValue)
+ fraction * (Color.red(endValue) - Color.red(startValue)));
int green = (int) (Color.green(startValue)
+ fraction * (Color.green(endValue) - Color.green(startValue)));
int blue = (int) (Color.blue(startValue)
+ fraction * (Color.blue(endValue) - Color.blue(startValue)));
return Color.argb(alpha, red, green, blue);
}
};
void draw(Canvas canvas) {
int offset = (int) (lineWidth * currPercent);
canvas.save();
canvas.translate(left, 0);
canvas.translate(offset, 0);
drawDefault(canvas);
canvas.restore();
}
private void drawDefault(Canvas canvas) {
int centerX = widthSize / 2;
int centerY = heightSize / 2;
int radius = (int) (widthSize * 0.5f);
// 陰影:隨 material 放大
defaultPaint.setStyle(Paint.Style.FILL);
canvas.save();
canvas.translate(0, radius * 0.25f);
canvas.scale(1 + (0.1f * material), 1 + (0.1f * material), centerX, centerY);
defaultPaint.setShader(shadowGradient);
canvas.drawCircle(centerX, centerY, radius, defaultPaint);
defaultPaint.setShader(null);
canvas.restore();
// 本體:顏色隨 material 漸變
defaultPaint.setStyle(Paint.Style.FILL);
defaultPaint.setColor(te.evaluate(material, 0xFFFFFFFF, 0xFFE7E7E7));
canvas.drawCircle(centerX, centerY, radius, defaultPaint);
// 邊框
defaultPaint.setStyle(Paint.Style.STROKE);
defaultPaint.setColor(0xFFD7D7D7);
canvas.drawCircle(centerX, centerY, radius, defaultPaint);
}
/** 手指抬起後,用動畫把狀態漸變回初始值 */
private void materialRestore() {
if (anim != null) anim.cancel();
anim = ValueAnimator.ofFloat(material, 0);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
material = (float) animation.getAnimatedValue();
invalidate();
}
});
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
material = 0;
invalidate();
}
});
anim.start();
}
}
原本 draw 中直接畫 bmp 的邏輯被 drawDefault 取代,兩者差異只有兩處:陰影做了 scale、按鈕本體做了顏色漸變。materialRestore 則負責在手指離開後開一條動畫把狀態平滑還原。

Range 的意思就是範圍,但光知道這個似乎沒什麼用。反覆摸索之後發現了規律:

把它們拆開來看,其實各自擁有固定的滑動區間;右邊的按鈕只不過是左邊按鈕向右平移了一個按鈕寬度。

public class RangeSeekBar extends View {
private SeekBar leftSB = new SeekBar();
private SeekBar rightSB = new SeekBar();
/** 記錄當前手指按下的究竟是哪一個按鈕 */
private SeekBar currTouch;
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// ...省略
// rightSB 緊緊貼在 leftSB 右側
rightSB.left += leftSB.widthSize;
rightSB.right += leftSB.widthSize;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// ...省略
leftSB.draw(canvas);
rightSB.draw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
boolean touchResult = false;
// 先檢測 rightSB:避免兩者重疊時誤判
if (rightSB.collide(event)) {
currTouch = rightSB;
touchResult = true;
} else if (leftSB.collide(event)) {
currTouch = leftSB;
touchResult = true;
}
return touchResult;
case MotionEvent.ACTION_MOVE:
float percent;
float x = event.getX();
if (currTouch == leftSB) {
if (x < lineLeft) {
percent = 0;
} else {
percent = (x - lineLeft) * 1f / (lineWidth - rightSB.widthSize);
}
// 左按鈕不得越過右按鈕
if (percent > rightSB.currPercent) {
percent = rightSB.currPercent;
}
leftSB.slide(percent);
} else if (currTouch == rightSB) {
if (x > lineRight) {
percent = 1;
} else {
percent = (x - lineLeft - leftSB.widthSize)
* 1f / (lineWidth - leftSB.widthSize);
}
// 右按鈕不得越過左按鈕
if (percent < leftSB.currPercent) {
percent = leftSB.currPercent;
}
rightSB.slide(percent);
}
invalidate();
break;
}
return super.onTouchEvent(event);
}
}
歸根究柢就是那一套:觸摸改變屬性值,再依屬性值繪製對應的 UI。自 SwitchButton 之後,又完整複習了一遍這個套路。



看起來還少了按壓狀態的變化,那就留給下一版吧。
OkHttp + Handler + LruCache 實作網路圖片快取(搭配通用 MVP 架構)
之前寫過一篇關於快取網路圖片的學習筆記,那時用的是 AsyncTask 非同步任務來做下載與快取。這次換個思路,改用 LruCache 來管理快取。 LruCache 是
40 條 Android 開發優化建議大整理
開始 Android 開發的好方法 初學者可以循以下步驟入手:先找一些與目標功能相近的範例程式碼,接著動手改寫讓它符合自己的需求,然後回顧開發過程中遇到的問題,最後善用
Android 中的日曆控件 CalendarView 使用教學
需要讓使用者選擇日期時,Android 內建的 CalendarView 日曆控件是個很方便的選擇。它以月曆的形式呈現,使用者點選日期後即可透過監聽器取得年、月、日資訊。
Android DNS 解析流程簡析
Android 的 DNS 相關程式碼主要位於 bionic/libc/netbsd 目錄中。雖然 netbsd 已不是活躍專案,但其中的 DNS 解析部分仍被 Andr