3

我有一个对话框,在应用程序首次启动时显示信息。由于这些天的用户,总是单击“确定”而不阅读文本。我想在前 5 秒内禁用 OK 按钮(最好在里面有倒计时)。如何实现?

我的代码(不是很有必要):

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

我希望这对其他用户有所帮助。

4

2 回答 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 秒后启用按钮。这看起来确实有点乱,但它确实有效。我欢迎任何有更清洁版本的人!

于 2013-06-08T11:22:49.103 回答
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)
    }
}
于 2020-12-31T10:19:56.373 回答