是的,我知道有AlertDialog。但我很惊讶地知道在Android中显示对话框有多么困难(好吧,至少不是程序员友好的)。
我曾经是一名。net开发人员,我想知道在android上是否有类似的功能?
if (MessageBox.Show("Sure?", "", MessageBoxButtons.YesNo) == DialogResult.Yes){
// Do something...
}
是的,我知道有AlertDialog。但我很惊讶地知道在Android中显示对话框有多么困难(好吧,至少不是程序员友好的)。
我曾经是一名。net开发人员,我想知道在android上是否有类似的功能?
if (MessageBox.Show("Sure?", "", MessageBoxButtons.YesNo) == DialogResult.Yes){
// Do something...
}
当前回答
AlertDialog.Builder altBx = new AlertDialog.Builder(this);
altBx.setTitle("My dialog box");
altBx.setMessage("Welcome, Please Enter your name");
altBx.setIcon(R.drawable.logo);
altBx.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
if(edt.getText().toString().length()!=0)
{
// Show any message
}
else
{
}
}
});
altBx.setNeutralButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
//show any message
}
});
altBx.show();
其他回答
Kotlin在Android::
override fun onBackPressed() {
confirmToCancel()
}
private fun confirmToCancel() {
AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Do you want to cancel?")
.setCancelable(false)
.setPositiveButton("Yes") {
dialog: DialogInterface, _: Int ->
dialog.dismiss()
// for sending data to previous activity use
// setResult(response code, data)
finish()
}
.setNegativeButton("No") {
dialog: DialogInterface, _: Int ->
dialog.dismiss()
}
.show()
}
Steve H的回答是正确的,但这里有更多的信息:对话框之所以以这种方式工作,是因为Android中的对话框是异步的(当对话框显示时,执行不会停止)。因此,您必须使用回调来处理用户的选择。
在关于Android和。net的区别(因为它涉及到对话框)的更长的讨论中,看看这个问题: 对话框/ alertdialog:如何在对话框启动时“阻止执行”(. net风格)
你可以在Kotlin中轻松完成:
alert("Testing alerts") {
title = "Alert"
yesButton { toast("Yess!!!") }
noButton { }
}.show()
芬兰湾的科特林的实现。
你可以像这样创建一个简单的函数:
fun dialogYesOrNo(
activity: Activity,
title: String,
message: String,
listener: DialogInterface.OnClickListener
) {
val builder = AlertDialog.Builder(activity)
builder.setPositiveButton("Yes", DialogInterface.OnClickListener { dialog, id ->
dialog.dismiss()
listener.onClick(dialog, id)
})
builder.setNegativeButton("No", null)
val alert = builder.create()
alert.setTitle(title)
alert.setMessage(message)
alert.show()
}
像这样叫它:
dialogYesOrNo(
this,
"Question",
"Would you like to eat?",
DialogInterface.OnClickListener { dialog, id ->
// do whatever you need to do when user presses "Yes"
}
})
AlertDialog.Builder altBx = new AlertDialog.Builder(this);
altBx.setTitle("My dialog box");
altBx.setMessage("Welcome, Please Enter your name");
altBx.setIcon(R.drawable.logo);
altBx.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
if(edt.getText().toString().length()!=0)
{
// Show any message
}
else
{
}
}
});
altBx.setNeutralButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
//show any message
}
});
altBx.show();