編輯:關於 Android 程式設計
早前曾經幫人做過一個圓形進度條,效果圖也貼出來給大家看過。結果對方並不滿意,提出原應用的三個關鍵行為:倒數的最後 5 秒才開始顯示數字、轉滿一圈的時間應該在 30 秒左右。我掐著秒錶實際測了一下,發現雖然我把總時長設成了 30s,實際跑完一圈卻要 50 多秒。
問題於是變得很明確:
折騰了一個小時,總算把上面三個問題都收拾乾淨了。老規矩,效果圖先上:

遇到完全沒頭緒的問題,反編譯看看別人是怎麼做的,往往是最快的捷徑。這裡用的是 Android 逆向助手。
翻完對方的代碼才明白,整個倒數節奏是靠 CountDownTimer 撐起來的:計時器週期 25ms,總時長 30000ms,每次 tick 都用剩餘時間反推進度,最後 5 秒才把數字顯示出來,並在數字「1」結束時播放一個縮放消失動畫。
public class MyProgressCount extends CountDownTimer {
public MyProgressCount() {
super(30000L, 25L);
}
@Override
public void onFinish() {
start();
}
@Override
public void onTick(long paramLong) {
count = max - (float) paramLong;
progress_bar.setProgress(count);
circleRadius = progressBar_width / 2;
circleX = window_width / 2 - circleRadius;
circleY = circleY_init + circleRadius;
if (count >= max - 200.0F) {
round_text.setVisibility(View.GONE);
password_time = DateUtils.getStringToDate(DateUtils.getCurrentDate()) + d_value;
count = 0.0F;
password = Util.DynamicPassword(uid, password_time - (password_time % 30L), token);
// 生成動態口令並寫入資料庫
...
}
if (count > max * 5.0F / 6.0F) {
float f = count / 1000.0F;
double d = Math.PI * 12.0F * f / 180.0D;
int i = (int) (Math.sin(d) * progress_bar.getWidth() / 2.0D);
int j = (int) (Math.cos(d) * progress_bar.getWidth() / 2.0D);
Util.setLayout(round_text, circleX + circleRadius - Math.abs(i), circleY - Math.abs(j));
int color = ColorUtils.evaluate((count / max - 0.75D) * 4.0D, -1853686, -3407872);
round_text.setBackgroundDrawable(Util.getRoundBg(color, 100));
round_text.setTextColor(Color.WHITE);
if (f >= 25.0F && f <= 30.0F) {
round_text.setVisibility(View.VISIBLE);
round_text.setText((int) (31.0F - f) + "");
if (f >= 29.0F && f < 30.0F && !scaleAnimation.hasStarted()) {
round_text.setAnimation(scaleAnimation);
scaleAnimation.start();
}
} else {
round_text.setVisibility(View.GONE);
}
}
}
}
思路其實不複雜:一個 TextView 沿著圓周移動,同時動態改變文字內容與背景圓角顏色,外圈再套一個 CircleProgressBar 負責畫弧線。裡面唯一稍微費勁的,是顏色隨進度漸變的那段計算。
整個項目牽涉四個類:工具類 Util、ColorUtils,界面類 TestActivity01、CircleProgressBar。先看進度條本身:
public class CircleProgressBar extends View {
private Paint mProgressPaint;
private Paint mProgressBgPaint;
private float mMax = 100;
private float mProgress = 0;
private float mStrokeWith;
private float unitAngle;
private int mProgressColor;
private int mProgressEndColor;
private int mProgressEndColor2;
private int c;
public CircleProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
loadStyledAttr(context, attrs, defStyleAttr);
initPaint();
}
// 12 點方向為起點,逆時針不填充,只畫描邊
private int getStartAngle() {
return -90;
}
private float getSweepAngel() {
return unitAngle * mProgress;
}
private void initPaint() {
mProgressPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mProgressPaint.setStyle(Paint.Style.STROKE);
mProgressPaint.setStrokeJoin(Paint.Join.ROUND);
mProgressPaint.setStrokeWidth(Util.dip2px(getContext(), 10.0F));
mProgressBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mProgressBgPaint.setStyle(Paint.Style.FILL);
}
private void loadStyledAttr(Context context, AttributeSet attrs, int defStyleAttr) {
mProgressColor = Color.parseColor("#ff48d502");
mProgressEndColor = Color.parseColor("#ffe3b70a");
mProgressEndColor2 = Color.parseColor("#ffcc0000");
mMax = 100;
mProgress = 0;
mStrokeWith = Util.dip2px(getContext(), 6.0F);
}
// 進度未過 75% 時,走綠到黃的漸變
private void onProgressChanged() {
c = ColorUtils.evaluate(mProgress / mMax * 1.5F, mProgressColor, mProgressEndColor);
mProgressPaint.setColor(c);
}
// 超過 75% 之後,走黃到紅的漸變
private void onProgressChangedEnd() {
c = ColorUtils.evaluate((mProgress / mMax - 0.75F) * 4.0F, mProgressEndColor, mProgressEndColor2);
mProgressPaint.setColor(c);
}
private void setUnitProgress() {
unitAngle = 360.0F / mMax;
}
@Override
protected void onDraw(Canvas canvas) {
drawProgressBg(canvas);
drawProgress(canvas);
}
public void setProgress(float progress) {
mProgress = progress;
if (progress <= mMax * 0.75D) {
onProgressChanged();
} else {
onProgressChangedEnd();
}
invalidate();
}
}
代碼看著長,真正在 onDraw 裡做的事只有兩件:畫底環、畫進度弧。
public class TestActivity01 extends AppCompatActivity {
private int circleRadius, circleX, circleY, circleY_init;
private int duration = 1200;
private float count = 0.0F;
private float max;
private MyProgressCount progressCount;
private CircleProgressBar progress_bar;
private TextView round_text;
private int window_width;
private int progressBar_width;
// 第一版動畫(1.0 -> 0.4)效果不如第二版,最終採用直接縮到 0
private Animation scaleAnimation = new ScaleAnimation(
1.0F, 0.0F, 1.0F, 0.0F,
Animation.RELATIVE_TO_SELF, 0.5F,
Animation.RELATIVE_TO_SELF, 0.5F);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acttivity_test);
init();
}
private void init() {
scaleAnimation.setDuration(duration);
max = 30000.0F;
circleY_init = Util.dip2px(this, 85.0F);
window_width = getWindowManager().getDefaultDisplay().getWidth();
progress_bar = findViewById(R.id.cpb);
round_text = findViewById(R.id.tv);
progress_bar.setMax(max);
// 等 View 測量完成拿到真實寬度後再啟動計時,避免一圈時長被縮放
progress_bar.setSizeChangeListener(new CircleProgressBar.SizeChangeListener() {
@Override
public void sizeChanged(int w, int h, int oldw, int oldh) {
progressBar_width = progress_bar.getWidth();
if (progressCount == null) {
progressCount = new MyProgressCount();
}
progressCount.start();
}
});
}
@Override
protected void onStop() {
super.onStop();
if (progressCount != null) {
progressCount.cancel();
progressCount = null;
}
}
}
這裡有個關鍵細節:計時器必須等 CircleProgressBar 完成測量、拿到真實寬高之後才啟動。之前一圈要跑 50 多秒,就是因為在尺寸未確定時就已經開始計時,後續的重新布局又把節奏拖亂了。
public class Util {
public static int dip2px(Context context, float dp) {
return (int) (dp * context.getResources().getDisplayMetrics().density + 0.5F);
}
// 注意:這裡用的是 FrameLayout.LayoutParams,所以外層容器必須是 FrameLayout
public static void setLayout(View view, int x, int y) {
ViewGroup.MarginLayoutParams lp =
new ViewGroup.MarginLayoutParams(view.getLayoutParams());
lp.setMargins(x - 14, y + 10, lp.width + x, lp.height + y);
view.setLayoutParams(new FrameLayout.LayoutParams(lp));
}
public static Drawable getRoundBg(int color, int radius) {
return new ShapeDrawable(new RoundRectShape(
new float[]{radius, radius, radius, radius, radius, radius, radius, radius},
null, null)) {{
getPaint().setColor(color);
}};
}
}
public class ColorUtils {
// 按比例在兩個顏色之間插值,逐通道運算
public static int evaluate(float fraction, int startValue, int endValue) {
int a = (startValue >> 24) & 0xFF, r = (startValue >> 16) & 0xFF;
int g = (startValue >> 8) & 0xFF, b = startValue & 0xFF;
int a2 = (endValue >> 24) & 0xFF, r2 = (endValue >> 16) & 0xFF;
int g2 = (endValue >> 8) & 0xFF, b2 = endValue & 0xFF;
return (int) (((a2 - a) * fraction) + a) << 24
| (int) (((r2 - r) * fraction) + r) << 16
| (int) (((g2 - g) * fraction) + g) << 8
| (int) (((b2 - b) * fraction) + b);
}
}
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="385dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_marginTop="85dp">
<com.example.tangxb.myapplication.CircleProgressBar
android:id="@+id/cpb"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<TextView
android:id="@+id/tv"
android:layout_width="20dp"
android:layout_height="20dp"
android:gravity="center"
android:textColor="#ff494949" />
</FrameLayout>
能自己還原的部分我都還原了,唯一偷懶的地方是沒有用自定義屬性去配顏色,而是直接寫在代碼裡。如果你要拿去做產品,建議把顏色、線寬、直徑都抽成 declare-styleable 屬性。
Android 網路編程:UDP 通信模型實作範例
什麼是 Android UDP? UDP 是 User Datagram Protocol 的簡稱,中文名為使用者資料包協定,是 OSI 參考模型中一種無連線的傳輸層協定
Android 隨機驗證碼實作:用 Canvas 畫出帶干擾的驗證碼圖片
在 Android 客戶端開發中,驗證碼有兩種用途,目的完全不同:簡訊驗證碼用於身分認證,主要透過 HTTP 等通訊協議向伺服器索取並校驗;圖形隨機驗證碼則多用於「限制或
Android 仿天貓下拉刷新自定義控制項深度解析
一、概述 本控制項以 android-Ultra-Pull-to-Refresh 為基礎,針對其 header 進行客製化擴充。它繼承自 PtrFrameLayout,
Android 自定義 View 入門:手把手畫出柱狀統計圖 BarGraphView
自定義 View 的教學網路上已經汗牛充棟,本文定位是給初學者的第一份參考:不追求炫技,只把「一個 View 是怎麼被畫到螢幕上」這件事講清楚,然後真的做出一張柱狀統計圖