編輯:關於 Android 程式設計
熟悉 iOS 的人應該知道有個 UISliderBar 控制項,iPhone 的「調整文字大小」就用了它。最近產品提出一個需求:讓使用者能調整 App 內部分字體的大小。技術難度不高,但工作量不小,思路是透過 LayoutInflater.Factory 來實現。UI 參考了 iOS 的 UISliderBar,而 Android 系統並沒有現成符合要求的控制項,於是動手寫了一個,取名 FontSliderBar,運行效果如下:


動手前先拆解一下 UISliderBar 的效果:它有刻度條
,上方還有一顆可拖動的圓球
。因此我們把畫刻度尺的部分抽成 Bar,把拖動的圓球抽成 Thumb,如拆分圖所示:
Thumb 負責在螢幕上繪製圓球。既然是繪製,就需要 Canvas(由外部傳入);要知道畫在哪,就需要 X、Y 座標(其中 X 可變、Y 固定);要畫多大、按下與放開時分別是什麼顏色,就需要半徑 radius 與 normalColor、pressedColor。此外還加了一個 mTouchZone 屬性,模擬 Android 的 TouchDelegate——當圓半徑太小、手指點不準時,用一個最小觸摸範圍來改善體驗。
public class Thumb {
private static final float MINIMUM_TARGET_RADIUS = 50;
private final float mTouchZone;
private boolean mIsPressed;
private final float mY;
private float mX;
private Paint mPaintNormal, mPaintPressed;
private float mRadius;
private int mColorNormal, mColorPressed;
public Thumb(float x, float y, int colorNormal, int colorPressed, float radius) {
mRadius = radius;
mColorNormal = colorNormal;
mColorPressed = colorPressed;
mPaintNormal = new Paint(); mPaintNormal.setColor(mColorNormal); mPaintNormal.setAntiAlias(true);
mPaintPressed = new Paint(); mPaintPressed.setColor(mColorPressed); mPaintPressed.setAntiAlias(true);
mTouchZone = (int) Math.max(MINIMUM_TARGET_RADIUS, radius);
mX = x; mY = y;
}
public void setX(float x) { mX = x; }
public float getX() { return mX; }
public boolean isPressed() { return mIsPressed; }
public void press() { mIsPressed = true; }
public void release() { mIsPressed = false; }
public boolean isInTargetZone(float x, float y) {
return Math.abs(x - mX) <= mTouchZone && Math.abs(y - mY) <= mTouchZone;
}
public void draw(Canvas canvas) {
canvas.drawCircle(mX, mY, mRadius, mIsPressed ? mPaintPressed : mPaintNormal);
}
public void destroyResources() { mPaintNormal = null; mPaintPressed = null; }
}
Bar 負責繪製刻度尺,同樣需要 X、Y 座標與 Canvas;此外要知道刻度尺多長、有多少刻度、每格高度、顏色,以及上方文字的大小與顏色。據此抽象出 Bar:
public class Bar {
private Paint mBarPaint, mTextPaint;
private final float mLeftX, mRightX, mY, mPadding;
private int mSegments;
private float mTickDistance;
private final float mTickHeight, mTickStartY, mTickEndY;
public Bar(float x, float y, float width, int tickCount, float tickHeight,
float barWidth, int barColor, int textColor, int textSize, int padding) {
mLeftX = x; mRightX = x + width; mY = y; mPadding = padding;
mSegments = tickCount - 1;
mTickDistance = width / mSegments;
mTickHeight = tickHeight;
mTickStartY = mY - mTickHeight / 2f;
mTickEndY = mY + mTickHeight / 2f;
mBarPaint = new Paint(); mBarPaint.setColor(barColor);
mBarPaint.setStrokeWidth(barWidth); mBarPaint.setAntiAlias(true);
mTextPaint = new Paint(); mTextPaint.setColor(textColor);
mTextPaint.setTextSize(textSize); mTextPaint.setAntiAlias(true);
}
public void draw(Canvas canvas) { drawLine(canvas); drawTicks(canvas); }
public float getLeftX() { return mLeftX; }
public float getRightX() { return mRightX; }
public float getNearestTickCoordinate(Thumb thumb) {
return mLeftX + (getNearestTickIndex(thumb) * mTickDistance);
}
public int getNearestTickIndex(Thumb thumb) { return getNearestTickIndex(thumb.getX()); }
public int getNearestTickIndex(float x) {
return (int) ((x - mLeftX + mTickDistance / 2f) / mTickDistance);
}
private void drawLine(Canvas canvas) {
canvas.drawLine(mLeftX, mY, mRightX, mY, mBarPaint);
}
private void drawTicks(Canvas canvas) {
for (int i = 0; i <= mSegments; i++) {
final float x = i * mTickDistance + mLeftX;
canvas.drawLine(x, mTickStartY, x, mTickEndY, mBarPaint);
String text = 0 == i ? "小" : mSegments == i ? "大" : "";
if (!TextUtils.isEmpty(text)) {
canvas.drawText(text, x - mTextPaint.measureText(text) / 2, mTickStartY - mPadding, mTextPaint);
}
}
}
public void destroyResources() { mBarPaint = null; mTextPaint = null; }
}
getNearestTickCoordinate() 用來找離 thumb 最近刻度的 X 座標,getNearestTickIndex() 則回傳最近刻度的索引。
FontSliderBar 繼承 View,重寫 onMeasure 決定尺寸。要特別注意:若寬高都設為 wrap_content 會出問題,所以要對寬高設最小值。最小高度可從刻度文字、文字間距與圓球直徑推算:
public class FontSliderBar extends View {
private int mTickCount = 3;
private float mTickHeight = 24, mBarWidth = 3;
private int mBarColor = Color.LTGRAY;
private float mThumbRadius = 20;
private int mThumbColorNormal = 0xff33b5e5, mThumbColorPressed = 0xff33b5e5;
private int mTextSize = 16, mTextColor = Color.LTGRAY, mTextPadding = 20;
private int mDefaultWidth = 500, mCurrentIndex = 0;
private boolean mAnimation = true;
private Thumb mThumb;
private Bar mBar;
private ValueAnimator mAnimator;
private OnSliderBarChangeListener mListener;
public FontSliderBar(Context context) { super(context); }
public FontSliderBar(Context context, AttributeSet attrs) { super(context, attrs); }
public FontSliderBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); }
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int wMode = MeasureSpec.getMode(widthMeasureSpec);
final int hMode = MeasureSpec.getMode(heightMeasureSpec);
final int wSize = MeasureSpec.getSize(widthMeasureSpec);
final int hSize = MeasureSpec.getSize(heightMeasureSpec);
int width = (wMode == MeasureSpec.EXACTLY) ? wSize
: (wMode == MeasureSpec.AT_MOST) ? wSize : mDefaultWidth;
int height = (hMode == MeasureSpec.EXACTLY) ? hSize
: (hMode == MeasureSpec.AT_MOST) ? Math.min(getMinHeight(), hSize) : getMinHeight();
setMeasuredDimension(width, height);
}
private int getMinHeight() {
return (int) (getFontHeight() + mTextPadding + mThumbRadius * 2);
}
@Override protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
createBar(); createThumbs();
}
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mBar.draw(canvas); mThumb.draw(canvas);
}
@Override public boolean onTouchEvent(MotionEvent event) {
if (!isEnabled() || isAnimationRunning()) return false;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: return onActionDown(event.getX(), event.getY());
case MotionEvent.ACTION_MOVE:
this.getParent().requestDisallowInterceptTouchEvent(true);
return onActionMove(event.getX());
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
this.getParent().requestDisallowInterceptTouchEvent(false);
return onActionUp(event.getX(), event.getY());
default: return true;
}
}
private boolean onActionDown(float x, float y) {
if (!mThumb.isPressed() && mThumb.isInTargetZone(x, y)) { mThumb.press(); invalidate(); }
return true;
}
private boolean onActionMove(float x) {
if (mThumb.isPressed()) {
if (x >= mBar.getLeftX() && x <= mBar.getRightX()) { mThumb.setX(x); invalidate(); }
}
return true;
}
private boolean onActionUp(float x, float y) {
if (mThumb.isPressed()) {
final int tempIndex = mBar.getNearestTickIndex(mThumb);
if (tempIndex != mCurrentIndex) {
mCurrentIndex = tempIndex;
if (mListener != null) mListener.onIndexChanged(this, mCurrentIndex);
}
float end = mBar.getNearestTickCoordinate(mThumb);
if (mAnimation) startAnimation(mThumb, mThumb.getX(), end);
else { mThumb.setX(end); invalidate(); }
mThumb.release();
}
return true;
}
private void startAnimation(final Thumb thumb, float start, float end) {
stopAnimation();
mAnimator = ValueAnimator.ofFloat(start, end);
mAnimator.setDuration(80);
mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override public void onAnimationUpdate(ValueAnimator a) {
thumb.setX((Float) a.getAnimatedValue()); invalidate();
}
});
mAnimator.start();
}
private boolean isAnimationRunning() { return mAnimator != null && mAnimator.isRunning(); }
private void stopAnimation() { if (mAnimator != null) { mAnimator.cancel(); mAnimator = null; } }
private void destroyResources() {
stopAnimation();
if (mBar != null) { mBar.destroyResources(); mBar = null; }
if (mThumb != null) { mThumb.destroyResources(); mThumb = null; }
}
private float getFontHeight() {
Paint paint = new Paint(); paint.setTextSize(mTextSize);
Paint.FontMetrics fm = paint.getFontMetrics();
return fm.descent - fm.ascent;
}
public interface OnSliderBarChangeListener {
void onIndexChanged(FontSliderBar rangeBar, int index);
}
}
FontSliderBar 定義了各項預設值,並對外提供了一系列可鏈式呼叫的屬性設定方法。它重寫了 onMeasure(決定尺寸)、onSizeChanged(建立 Bar 與 Thumb)、onDraw(繪製)、onTouchEvent(依點擊判斷是否拖動),最後透過 OnSliderBarChangeListener 介面在索引變化時回調。使用時可以鏈式設定屬性:
FontSliderBar sliderBar = (FontSliderBar) findViewById(R.id.sliderbar);
sliderBar.setTickCount(6).setTickHeight(30).setBarColor(Color.MAGENTA)
.setTextColor(Color.CYAN).setTextPadding(20).setTextSize(20)
.setThumbRadius(20).setThumbColorNormal(Color.CYAN).setThumbColorPressed(Color.GREEN)
.withAnimation(false).applay();
運行效果如下:

關於 FontSliderBar 的講解就告一段落,感謝收看~
自訂控制項實作:可拖拽排序的 ListView
前言最近研究了可拖拽排序的 ListView,效果類似酷狗裡的播放清單排序。但因為要加入自己特有的功能,我折騰了好一段時間。最初接觸的是 GitHub 上的開源專案 Dr
用 Paint 與 Canvas 手繪棋盤:Android 自訂 View 入門
自訂 View 的繪圖基本配備就是 Paint 與 Canvas 這兩個類別。這篇用「畫一個象棋棋盤」當練習題,主要用到畫線與畫圓兩個方法: · drawLine(起始x
Android App 簽名(證書)校驗過程源碼深度解析
Android App 的安裝離不開證書支持。我們在 Eclipse 或 Android Studio 中開發時,往往注意不到證書的存在也能正常安裝,那是因為使用了默認的
Android 錄影實作:用 MediaRecorder 錄製視頻
錄影的一般流程是從相機與麥克風取得原始資料,經過編碼後寫成檔案。Android 這件事交給 MediaRecorder 負責——它不只錄音,也能錄製視頻。 成品預覽