需求:點擊「加關注」→ 顯示 ProgressDialog → 3 秒後關閉 → 文字變「已關注」 → 彈 Toast;再次點擊反向操作。原代碼中 Toast 與 Dialog 同時出現,且子線程 sleep 不阻塞主線程,導致時序混亂。
在 UI 線程用 Handler.sendEmptyMessageDelayed 控制時序,避免手動開線程 sleep。
private Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
dialog.dismiss();
button.setEnabled(true);
button.setText(isFollowing ? "加關注" : "已關注");
Toast.makeText(MainActivity.this,
isFollowing ? "取消關注成功" : "關注成功",
Toast.LENGTH_SHORT).show();
isFollowing = !isFollowing;
}
};
button.setOnClickListener(v -> {
button.setEnabled(false);
dialog = ProgressDialog.show(this, "", isFollowing ? "取消關注中..." : "關注中...", true);
mHandler.sendEmptyMessageDelayed(0, 3000); // 3 秒後處理 UI 更新
});
若需網絡請求,將 handleMessage 中的邏輯換為發起請求,請求回調再發送消息更新 UI。