編輯:關於 Android 程式設計
(一)概述

ProgressBar 是 Android 裡反饋「正在進行中」的基礎控件。它既可以表達確定的百分比,也可以表達不確定的忙碌狀態。
(二)常用屬性與基礎實例
從官方 API 的類繼承關係可以看到它的位置:


常用屬性:

對應到 Java 代碼,可以調用這些方法:

先看看系統現成的樣式:

xml 文件:
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android_progressbar.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="小圓形進度條" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="中型圓形進度條" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="大型圓形進度條" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="水平進度條" />
<ProgressBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="30" />
<ProgressBar
android:id="@+id/progressbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:max="100"
android:progress="30"
android:secondaryProgress="60" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="增加進度" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="減小進度" />
</LinearLayout>
</LinearLayout>
java 文件:
public class MainActivity extends Activity implements OnClickListener {
private ProgressBar progressBar;
private Button button1, button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 讓窗口支持帶刻度的進度效果
requestWindowFeature(Window.FEATURE_PROGRESS);
// 設置 ActionBar 中最右側的不確定進度條
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
setProgressBarVisibility(true); // 激活進度條
setProgressBarIndeterminate(true); // 不確定模式
setProgress(3500);
button1 = (Button) this.findViewById(R.id.button1);
button2 = (Button) this.findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
progressBar.setProgress((int) (progressBar.getProgress() * 1.2));
progressBar.setSecondaryProgress((int) (progressBar.getSecondaryProgress() * 1.2));
break;
case R.id.button2:
progressBar.setProgress((int) (progressBar.getProgress() * 0.8));
progressBar.setSecondaryProgress((int) (progressBar.getSecondaryProgress() * 0.8));
break;
}
}
}
代碼很直白,註釋也在裡面。不過實際項目裡很少直接用系統默認樣式——原因就一個字:醜。那有沒有更好的辦法?有。
(三)用動畫替換原始進度條

想做一個「菊花」轉圈效果,先準備好逐幀圖片資源,再定義一個 AnimationDrawable。
效果圖:

xml 文件:
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android_progressbar.MainActivity">
<ImageView
android:id="@+id/imageView1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:layout_marginTop="200dp"
android:src="@drawable/anim_pgbar" />
</LinearLayout>
java 代碼:
public class MainActivity2 extends Activity {
private ImageView img_pgbar;
private AnimationDrawable ad;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
img_pgbar = (ImageView) findViewById(R.id.imageView1);
ad = (AnimationDrawable) img_pgbar.getDrawable();
img_pgbar.postDelayed(new Runnable() {
@Override
public void run() {
ad.start();
}
}, 100);
}
}
延遲 100ms 再 start 是為了確保 Drawable 已經完成初始化,直接同步調用有時會拿不到可用狀態。

(四)自定義圓形進度條

官方 API 文檔其實給了明確建議:
public class MyActivity extends Activity {
private static final int PROGRESS = 0x1;
private ProgressBar mProgress;
private int mProgressStatus = 0;
private Handler mHandler = new Handler();
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.progressbar_activity);
mProgress = (ProgressBar) findViewById(R.id.progress_bar);
// 把耗時操作放到後台線程
new Thread(new Runnable() {
public void run() {
while (mProgressStatus < 100) {
mProgressStatus = doWork();
// 通過 Handler 更新進度條
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
}
}
}).start();
}
}
思路很清楚:耗時計算放子線程,UI 更新交給 Handler 切回主線程。下面照這個思路自己畫一個圓形進度條。
運行結果:

實現代碼:
package com.example.android_progressbar;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
public class CirclePgBar extends View {
private Paint mBackPaint;
private Paint mFrontPaint;
private Paint mTextPaint;
private float mStrokeWidth = 50;
private float mHalfStrokeWidth = mStrokeWidth / 2;
private float mRadius = 200;
private RectF mRect;
private int mProgress = 0; // 當前進度
private int mTargetProgress = 100; // 目標進度
private int mMax = 100;
private int mWidth;
private int mHeight;
public CirclePgBar(Context context) {
super(context);
init();
}
public CirclePgBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CirclePgBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
/** 完成相關參數初始化 */
private void init() {
mBackPaint = new Paint();
mBackPaint.setColor(Color.WHITE);
mBackPaint.setAntiAlias(true);
mBackPaint.setStyle(Paint.Style.STROKE);
mBackPaint.setStrokeWidth(mStrokeWidth);
mFrontPaint = new Paint();
mFrontPaint.setColor(Color.GREEN);
mFrontPaint.setAntiAlias(true);
mFrontPaint.setStyle(Paint.Style.STROKE);
mFrontPaint.setStrokeWidth(mStrokeWidth);
mTextPaint = new Paint();
mTextPaint.setColor(Color.GREEN);
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(80);
mTextPaint.setTextAlign(Paint.Align.CENTER);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mWidth = getRealSize(widthMeasureSpec);
mHeight = getRealSize(heightMeasureSpec);
setMeasuredDimension(mWidth, mHeight);
}
@Override
protected void onDraw(Canvas canvas) {
initRect();
float angle = mProgress / (float) mMax * 360;
canvas.drawCircle(mWidth / 2, mHeight / 2, mRadius, mBackPaint);
canvas.drawArc(mRect, -90, angle, false, mFrontPaint);
canvas.drawText(mProgress + "%", mWidth / 2 + mHalfStrokeWidth,
mHeight / 2 + mHalfStrokeWidth, mTextPaint);
if (mProgress < mTargetProgress) {
mProgress += 1;
invalidate();
}
}
public int getRealSize(int measureSpec) {
int result = 1;
int mode = MeasureSpec.getMode(measureSpec);
int size = MeasureSpec.getSize(measureSpec);
if (mode == MeasureSpec.AT_MOST || mode == MeasureSpec.UNSPECIFIED) {
// 自行計算默認尺寸
result = (int) (mRadius * 2 + mStrokeWidth);
} else {
result = size;
}
return result;
}
private void initRect() {
if (mRect == null) {
mRect = new RectF();
int viewSize = (int) (mRadius * 2);
int left = (mWidth - viewSize) / 2;
int top = (mHeight - viewSize) / 2;
int right = left + viewSize;
int bottom = top + viewSize;
mRect.set(left, top, right, bottom);
}
}
}
本質就是一個自定義 View:三個 Paint 分別畫底環、進度弧和文字,onDraw 裡用 drawArc 從 12 點方向(-90 度)開始掃描,每畫一幀 mProgress 加一並 invalidate 觸發下一幀。
xml 代碼:
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android_progressbar.MainActivity">
<com.example.android_progressbar.CirclePgBar
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Android 四大組件入門:BroadcastReceiver 廣播接收器完整指南
學習 Android 一段時間後,回頭整理 BroadcastReceiver 的使用方式,會發現它是四大組件中既簡單又容易忽略的一環。它不像 Activity 那樣直接
Android 網絡開發實戰:Volley 入門與 Cloudant 通訊(一)
引言 網絡一直是我的知識盲點,前陣子我抽空系統學習了 Volley 這個網絡工具的使用,並進一步研讀了它的源碼,頗有心得,想在此分享。Android 平台上成熟的網絡庫並
Android 實作「獲取驗證碼」倒數計時按鈕
功能很單純:點一下按鈕發送驗證碼,然後按鈕進入 60 秒倒數,倒數期間不可再點,結束後恢復。這類互動在註冊、找回密碼頁面幾乎必備。 實作核心只有一個類:CountDown
vivo X7怎麼換字型?替換系統字型檔案的步驟與風險
有些使用者對 vivo X7 的系統預設字型不太滿意,想換成自己喜歡的樣式。這件事在 Android 上做得到,但需要解鎖系統權限並替換字型檔案,屬於高風險操作,請先讀完