編輯:關於 Android 程式設計
前陣子在技術問答區看到一個提問:怎麼實現「加載中…」後面那三個點依次閃動的效果?看起來只是個不起眼的細節,可真要動手,一時之間還想不出特別優雅的方案。折騰了一輪之後,最終用最樸素的方式把它跑了起來。

整體的做法是自定義一個 Dialog,把「加載中」的視覺效果封裝在 Dialog 內部,而真正的業務進度仍然由 Activity 那邊驅動。兩者各司其職,耦合度很低。
CustomDialog 繼承自 AlertDialog,在 onCreate 裡完成布局加載、寬度設置、定時器啟動以及銷毀時的資源回收。
public class CustomDialog extends AlertDialog {
private TextView tv_loading;
private ProgressBar progressBar;
private Timer timer;
private int count = 1;
public CustomDialog(Context context) {
super(context);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_progress);
tv_loading = (TextView) findViewById(R.id.tv_loading);
progressBar = (ProgressBar) findViewById(R.id.pb);
// 讓 Dialog 的寬度佔屏幕寬度的 80%
Display d = getWindow().getWindowManager().getDefaultDisplay();
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.width = (int) (d.getWidth() * 0.8);
getWindow().setAttributes(lp);
// 每 300 毫秒觸發一次,形成點號跳動的節奏
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
handler.sendEmptyMessage(0);
}
}, 300, 300);
// Dialog 關閉時務必停止定時器,避免內存洩漏
setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
if (timer != null) {
timer.cancel();
}
}
});
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
count++;
if (count > 3) {
count = 1;
}
switch (count) {
case 1:
tv_loading.setText("加載中.");
break;
case 2:
tv_loading.setText("加載中..");
break;
case 3:
tv_loading.setText("加載中...");
break;
}
}
};
// 對外暴露的進度接口,達到 100 就自動關閉
public void setProgress(int progress) {
progressBar.setProgress(progress);
if (progress == 100) {
this.dismiss();
}
}
}
結構很簡單,一個顯示文案的 TextView 加一條水平 ProgressBar,背景使用自定義的圆角 shape。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/shape_dialog_bg"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="@+id/tv_loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="加載中..."
android:textSize="16sp" />
<ProgressBar
android:id="@+id/pb"
android:layout_width="match_parent"
android:layout_height="10dp"
android:max="100"
android:progressDrawable="@drawable/layer_list_progress_drawable" />
</LinearLayout>
進度條的圓角樣式在另一篇《Android 自定義水平進度條的圓角進度》裡已經詳細寫過,這裡不再重複。
public class MainActivity extends FragmentActivity {
private CustomDialog customDialog;
private int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customDialog = new CustomDialog(this);
}
public void tvClick(View view) {
customDialog.show();
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
count += 10;
runOnUiThread(new Runnable() {
@Override
public void run() {
if (customDialog != null && customDialog.isShowing()) {
customDialog.setProgress(count);
}
}
});
if (count >= 100) {
timer.cancel();
}
}
}, 0, 500);
customDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
if (timer != null) timer.cancel();
count = 0;
}
});
}
}
這裡同樣用 Timer 來模擬進度遞增。實測下來,Timer 的定時操作比另外兩種常見方式寫起來更順手,語義也更直觀。
點擊事件我是直接在 XML 裡用 onClick 綁定的:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:clickable="true"
android:onClick="tvClick"
android:padding="10dp"
android:text="點擊彈框" />
第一個坑是 clickable。不加 android:clickable="true",部分機型(比如之前遇到的小米)默認並不會觸發 click 事件,怎麼點都沒反應。
第二個坑是作用域。這種 XML 直接綁定的寫法在 Fragment 裡是不可用的,Fragment 場景下只能老老实實用 setOnClickListener。
感謝網友 IT-hero 的提醒,其實這個需求用 ValueAnimator 會乾淨得多,不必再為一個「點號動畫」專門開一條定時器線程。改動集中在 onCreate 裡:
private String[] scoreText = {". ", ".. ", "..."};
ValueAnimator valueAnimator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_progress);
tv_loading = (TextView) findViewById(R.id.tv_loading);
progressBar = (ProgressBar) findViewById(R.id.pb);
Display d = getWindow().getWindowManager().getDefaultDisplay();
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.width = (int) (d.getWidth() * 0.8);
getWindow().setAttributes(lp);
if (valueAnimator == null) {
valueAnimator = ValueAnimator.ofInt(0, 3).setDuration(1000);
valueAnimator.setRepeatCount(ValueAnimator.INFINITE);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int i = (int) animation.getAnimatedValue();
tv_loading.setText("加載中" + scoreText[i % scoreText.length]);
}
});
}
valueAnimator.start();
}
// 其餘代碼省略
用 ofInt(0, 3) 配合 INFINITE 重複,再對取模結果做下標查表,邏輯一目了然,也不需要手動管理定時器的取消。順帶一提,記得在 Dialog 的 onDismiss 裡把動畫 stop 掉,道理和前面取消 Timer 一樣。
以上就是本文的全部內容,希望對大家的學習有所幫助。
Android 網絡編程:獲取並解析網絡上的 XML
要在 App 中取得網絡上的 XML,同樣需要伺服器端配合。本文以「最新資訊列表」為例,走一遍伺服器產生 XML、客戶端抓取並解析的完整流程。 一、建立伺服器端 專案結構
Android 子控制項超出父容器顯示:clipChildren 技巧
在製作底部導航或懸浮按鈕時,常會遇到子控制項被父容器裁切的問題。若希望子 View 能超出父 View 範圍顯示,可以在根配置加入 android:clipChildre
打飛機遊戲終章:Android 實戰實現 BOSS 戰與勝負結算
本文是打飛機遊戲系列的最後一篇,重點講 BOSS 的設計與勝負結算界面的處理。一、子彈類的擴展BOSS 需要發射八個方向的子彈,所以子彈類要支持方向屬性。在原有基礎上增加
手把手教你打造 Slack 風格的 Loading 動畫
專案地址:https://github.com/JeasonWong/SlackLoadingView 老規矩,先看效果。 圖有點大…… 說一下第一眼看到這個動畫後的思