編輯:關於 Android 程式設計
在實際開發中,系統自帶的 ProgressBar 往往難以滿足個性化設計的需求。本文以一個「帶刻度、並在進度條上顯示數值」的水平進度條為例,完整走一遍自定義 View 的關鍵步驟。

無論要實現怎樣的效果,自定義控件大致都繞不開以下幾個環節:
1. 自定義屬性的聲明與獲取;
2. 測量 onMeasure;
3. 布局 onLayout(ViewGroup);
4. 繪製 onDraw;
5. onTouchEvent;
6. onInterceptTouchEvent(ViewGroup);
7. 狀態的保存與恢復(與 Activity 生命週期相關)。
首先在 values 目錄下建立 attr.xml,聲明進度條所需的屬性,總共七個參數:進度條文字的顏色①與大小②、已走過進度條的顏色③與高度④、未走過進度條的顏色⑤與高度⑥,以及數值與進度條之間間隔的寬度⑦。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="horizonalPrograssBarWithPrograss">
<attr name="text_size" format="dimension" />
<attr name="text_color" format="color" />
<attr name="prograss_text_offset" format="dimension" />
<attr name="prograss_unreach_color" format="color" />
<attr name="prograss_unreach_height" format="dimension" />
<attr name="prograss_reach_color" format="color" />
<attr name="prograss_reach_height" format="dimension" />
</declare-styleable>
</resources>
新建名為 View 的包,並在其中創建 horizonalPrograssBarWithPrograss 類,繼承自 ProgressBar:
package com.chase.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ProgressBar;
import com.chase.cn.customprograssbar.R;
public class horizonalPrograssBarWithPrograss extends ProgressBar {
private static final int DEFAULT_TEXT_SIZE = 10; // sp
private static final int DEFAULT_TEXT_COLOR = 0xFFC00D1;
private static final int DEFAULT_COLOR_UNREACH = 0XFFD3D6DA;
private static final int DEFAULT_HEIGHT_UNREACH = 2; // dp
private static final int DEFAULT_COLOR_REACH = 0xFFC00D1;
private static final int DEFAULT_HRIGHT_REACH = 2; // dp
private static final int DEFAULT_TEXT_OFFSET = 10; // dp
private int mTextSize = dp2px(DEFAULT_TEXT_SIZE);
private int mTextColor = DEFAULT_TEXT_COLOR;
private int mUnReachColor = DEFAULT_COLOR_UNREACH;
private int mUnReachHeight = DEFAULT_HEIGHT_UNREACH;
private int mReachColor = DEFAULT_COLOR_REACH;
private int mReachHeight = DEFAULT_HRIGHT_REACH;
private int mTextOffset = dp2px(DEFAULT_TEXT_OFFSET);
private Paint mPaint = new Paint();
private int mRealWidth; // 進度條實際寬度
public horizonalPrograssBarWithPrograss(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public horizonalPrograssBarWithPrograss(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
obtainStyledAttrs(attrs);
}
private void obtainStyledAttrs(AttributeSet attrs) {
TypedArray ta = getContext().obtainStyledAttributes(
attrs, R.styleable.horizonalPrograssBarWithPrograss);
mTextSize = (int) ta.getDimension(
R.styleable.horizonalPrograssBarWithPrograss_text_size, mTextSize);
mTextColor = ta.getColor(
R.styleable.horizonalPrograssBarWithPrograss_text_color, mTextColor);
mTextOffset = (int) ta.getDimension(
R.styleable.horizonalPrograssBarWithPrograss_prograss_text_offset, mTextOffset);
mUnReachColor = ta.getColor(
R.styleable.horizonalPrograssBarWithPrograss_prograss_unreach_color, mUnReachColor);
mUnReachHeight = (int) ta.getDimension(
R.styleable.horizonalPrograssBarWithPrograss_prograss_unreach_height, mUnReachHeight);
mReachColor = ta.getColor(
R.styleable.horizonalPrograssBarWithPrograss_prograss_reach_color, mReachColor);
mReachHeight = (int) ta.getDimension(
R.styleable.horizonalPrograssBarWithPrograss_prograss_reach_height, mReachHeight);
mPaint.setTextSize(mTextSize);
ta.recycle();
}
@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthVal = MeasureSpec.getSize(widthMeasureSpec);
int height = measureHeight(heightMeasureSpec);
setMeasuredDimension(widthVal, height);
mRealWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
}
private int measureHeight(int heightMeasureSpec) {
int result = 0;
int mode = MeasureSpec.getMode(heightMeasureSpec);
int size = MeasureSpec.getSize(heightMeasureSpec);
if (mode == MeasureSpec.EXACTLY) {
result = size;
} else {
int textHeight = (int) (mPaint.descent() - mPaint.ascent());
result = getPaddingTop() + getPaddingBottom()
+ Math.max(Math.max(mReachHeight, mUnReachHeight), Math.abs(textHeight));
if (mode == MeasureSpec.AT_MOST) {
result = Math.min(result, size);
}
}
return result;
}
public horizonalPrograssBarWithPrograss(Context context) {
this(context, null);
}
@Override
protected synchronized void onDraw(Canvas canvas) {
canvas.save();
canvas.translate(getPaddingLeft(), getHeight() / 2);
boolean noNeedUnReach = false;
String text = getProgress() + "";
int textWidth = (int) mPaint.measureText(text);
float ratio = getProgress() * 1.0f / getMax();
float prograssX = ratio * mRealWidth;
if (prograssX + textWidth > mRealWidth) {
prograssX = mRealWidth - textWidth;
noNeedUnReach = true;
}
float endX = prograssX - mTextOffset / 2;
if (endX > 0) {
mPaint.setColor(mReachColor);
mPaint.setStrokeWidth(mReachHeight);
canvas.drawLine(0, 0, endX, 0, mPaint);
}
mPaint.setColor(mTextColor);
int y = (int) (-(mPaint.descent() + mPaint.ascent()) / 2);
canvas.drawText(text, prograssX, y, mPaint);
if (!noNeedUnReach) {
float start = prograssX + mTextOffset / 2 + textWidth;
mPaint.setColor(mUnReachColor);
mPaint.setStrokeWidth(mReachHeight);
canvas.drawLine(start, 0, mRealWidth, 0, mPaint);
}
canvas.restore();
}
private int dp2px(int dpVal) {
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, dpVal, getResources().getDisplayMetrics());
}
}
進度條的繪製至此完成。這裡比較關鍵的一點是文字高度的測量,它直接影響到自適應高度時的結果,如下圖所示:

接著在 activity_main.xml 中定義並測試:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:chase="https://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.chase.view.horizonalPrograssBarWithPrograss
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:padding="5dp"
android:progress="50" />
<com.chase.view.horizonalPrograssBarWithPrograss
android:id="@+id/prograss2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:padding="5dp"
android:progress="0"
chase:prograss_reach_height="5dp"
chase:prograss_unreach_color="#000"
chase:prograss_unreach_height="5dp"
chase:text_color="#44ff0000"
chase:text_size="10sp" />
</LinearLayout>
</ScrollView>
如上面所示,要使用自定義屬性,只需在根布局中聲明命名空間。在 Android Studio 中寫作:
xmlns:chase="https://schemas.android.com/apk/res-auto"
而在 Eclipse 中,則需跟隨 Manifest 中顯示的包名:
xmlns:chase="https://schemas.android.com/apk/com.chase.cn.customprograssbar"
下面用 Handler 對第二個進度條進行動態演示:
package com.chase.cn.customprograssbar;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import com.chase.view.horizonalPrograssBarWithPrograss;
public class MainActivity extends AppCompatActivity {
private horizonalPrograssBarWithPrograss mPrograss;
private static final int MSG_UPDATE = 0x111;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
int prograss = mPrograss.getProgress();
mPrograss.setProgress(++prograss);
if (prograss >= 100) {
handler.removeMessages(MSG_UPDATE);
} else {
handler.sendEmptyMessageDelayed(MSG_UPDATE, 100);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPrograss = (horizonalPrograssBarWithPrograss) findViewById(R.id.prograss2);
handler.sendEmptyMessage(MSG_UPDATE);
}
}
通過以上步驟,一個支持自定義顏色、高度、文字樣式與間距的水平進度條便完成了。整個過程的核心,正是自定義屬性的獲取、測量邏輯的處理以及 onDraw 的巧妙繪製。
Android自定義下拉刷新控件(下):為RefreshListView添加加載更多
本篇在自定義下拉刷新控件的基礎上,進一步為它加上「加載更多」的能力,讓列表在滑到底部時能自動觸發加載。先看最終的樣式效果: 1. 創建底部布局layout_foote
在 Activity、Service、Window 中監聽 Home 鍵與返回鍵的實踐与思考
關於按鍵監聽,相信很多人都已經很熟悉,所以本文不會在基礎部分花費太多筆墨,而是重點探討後半段——如何把監聽到的事件「傳遞出來」,尤其是在 Window 場景下的巧妙做法。
Android 線程池完全解析:調度原理、參數含義與實務封裝
一、線程到底是怎麼跑的 很多人對「多線程」有個誤會,以為開了十個線程就真的十件事同時在跑。真實情況要分兩種: 單核 CPU 在同一瞬間只能執行一個線程;多核 CPU 才能
Android Service 服務完整指南:分類、生命週期與使用時機
上一篇談到通知欄 Notification,說到通知欄就不得不提 Service 與 BroadcastReceiver。作為 Android 四大元件中的兩員,它們幾乎