我有一个对话框,可在应用首次启动时显示信息。由于这些天用户,总是点击“确定”而不阅读文本。我想在前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();
我希望这对其他用户有帮助。
答案 0 :(得分:10)
你走了:
// 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秒后启用按钮。这看起来有点乱,但它确实有效。我欢迎任何拥有更清洁版本的人!
答案 1 :(得分: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)
}
}