在x秒后启用AlertDialog“确定”按钮。

3
我有一个对话框,在应用程序第一次启动时显示信息。由于现今的用户总是在不阅读文本的情况下点击“确定”,我想在前5秒禁用“确定”按钮(最好内部带倒计时)。如何实现这个目标?
我的代码(不是很必要):
  new AlertDialog.Builder(this)
        .setMessage("Very usefull info here!")
        .setPositiveButton("OK", new android.content.DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
             ((AlertDialog)dialog).getButton(which).setVisibility(View.INVISIBLE);
             // the rest of your stuff
        }
        })
        .show();

我希望你对其他用户也有所帮助。
2个回答

11

给你:

// Create a handler
Handler handler = new Handler();

// Build the dialog
AlertDialog dialog = new AlertDialog.Builder(this)
    .setMessage("Very usefull info here!")
    .setPositiveButton("OK", new android.content.DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // the rest of your stuff
    }
})
.create();

dialog.show();

// Access the button and set it to invisible
final Button button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
button.setVisibility(View.INVISIBLE);

// Post the task to set it visible in 5000ms         
handler.postDelayed(new Runnable(){
    @Override
    public void run() {
        button.setVisibility(View.VISIBLE); 
    }}, 5000);

这将在5秒后启用按钮。虽然看起来有些混乱,但它有效。我欢迎任何有更简洁版本的人!


0
一个带有倒计时的 Kotlin 实现。计数器不太好看,但对于这个来说还可以。
@SuppressLint("SetTextI18n") // counter, nothing to translate
private fun setApproveDialog() {

    val label = getString(R.string.ok)
    
    val alert = AlertDialog.Builder(requireActivity())
        .setTitle(getString(R.string.approve_task).toUpperCase(Locale.ROOT))
        .setMessage(getString(R.string.approve_task_warning))
        .setCancelable(true)
        .setPositiveButton("$label - 3") { dialogInterface, _ ->
            setApprove()
            dialogInterface.dismiss()
        }
        .setNegativeButton(getString(R.string.back)) { dialogInterface, _ ->
            dialogInterface.dismiss()
        }
        .create()

    alert.show()

    val button = alert.getButton(AlertDialog.BUTTON_POSITIVE)

    button.isEnabled = false

    with(Handler(Looper.getMainLooper())) {
        postDelayed({ if (alert.isShowing) button.text = "$label - 2" }, 1000)
        postDelayed({ if (alert.isShowing) button.text = "$label - 1" }, 2000)
        postDelayed({
            if (alert.isShowing) {
                button.text = label
                button.isEnabled = true
            }
        }, 3000)
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接