Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自定義 Dialog:讓「加載中…」的三個點動起來

編輯:關於 Android 程式設計

從一個小需求說起

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

整體的做法是自定義一個 Dialog,把「加載中」的視覺效果封裝在 Dialog 內部,而真正的業務進度仍然由 Activity 那邊驅動。兩者各司其職,耦合度很低。

自定義 Dialog 的核心實現

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();
        }
    }
}

布局文件 dialog_progress.xml

結構很簡單,一個顯示文案的 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 自定義水平進度條的圓角進度》裡已經詳細寫過,這裡不再重複。

Activity 側如何驅動進度

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 一樣。

以上就是本文的全部內容,希望對大家的學習有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved