是的,我知道有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...
}
当前回答
史蒂夫的回答是正确的,尽管有些片段过时了。下面是一个FragmentDialog的例子。
类:
public class SomeDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("Title")
.setMessage("Sure you wanna do this!")
.setNegativeButton(android.R.string.no, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do nothing (will close dialog)
}
})
.setPositiveButton(android.R.string.yes, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do something
}
})
.create();
}
}
开始对话:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Create and show the dialog.
SomeDialog newFragment = new SomeDialog ();
newFragment.show(ft, "dialog");
您还可以让类实现onClickListener,并使用它来代替嵌入式侦听器。
其他回答
这里所有的答案都归结为冗长且不利于读者的代码:这正是提问者试图避免的。对我来说,最简单的方法是在这里使用lambdas:
new AlertDialog.Builder(this)
.setTitle("Are you sure?")
.setMessage("If you go back you will loose any changes.")
.setPositiveButton("Yes", (dialog, which) -> {
doSomething();
dialog.dismiss();
})
.setNegativeButton("No", (dialog, which) -> dialog.dismiss())
.show();
Android中的Lambdas需要retrolambda插件(https://github.com/evant/gradle-retrolambda),但无论如何,它对编写更清晰的代码非常有帮助。
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()
}
显示对话框匿名作为命令链&没有定义另一个对象:
new AlertDialog.Builder(this).setTitle("Confirm Delete?")
.setMessage("Are you sure?")
.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Perform Action & Dismiss dialog
dialog.dismiss();
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
})
.create()
.show();
谢谢。我使用API级别2 (Android 1.1),而不是BUTTON_POSITIVE和BUTTON_NEGATIVE,我必须使用BUTTON1和BUTTON2。
在芬兰湾的科特林:
AlertDialog.Builder(this)
.setTitle(R.string.question_title)
.setMessage(R.string.question_message)
.setPositiveButton(android.R.string.yes) { _, _ -> yesClicked() }
.setNegativeButton(android.R.string.no) { _, _ -> noClicked() }
.show()