如何在Android上显示Yes/No对话框?

是的,我知道有AlertDialog。但我很惊讶地知道在Android中显示对话框有多么困难(好吧,至少不是程序员友好的)。

我曾经是一名。net开发人员,我想知道在android上是否有类似的功能?

if (MessageBox.Show("Sure?", "", MessageBoxButtons.YesNo) == DialogResult.Yes){
// Do something...
}
345372 次浏览

AlertDialog。Builder真的没有那么难用。一开始肯定有点吓人,但一旦你使用了一点,它就变得简单而强大了。我知道你说过你知道如何使用它,但这里只是一个简单的例子:

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
break;


case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};


AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();

如果你有其他应该做同样事情的是/否框,你也可以重用那个DialogInterface.OnClickListener

如果你在View.OnClickListener中创建对话框,你可以使用view.getContext()来获取Context。或者你也可以使用yourFragmentName.getActivity()

Steve H的回答是正确的,但这里有更多的信息:对话框之所以以这种方式工作,是因为Android中的对话框是异步的(当对话框显示时,执行不会停止)。因此,您必须使用回调来处理用户的选择。

看看这个问题,关于Android和。net的区别(因为它涉及到对话框)的更长的讨论: 对话框/ alertdialog:如何“阻止执行”当对话框启动时(. net风格) < / p >

谢谢。我使用API级别2 (Android 1.1),而不是BUTTON_POSITIVEBUTTON_NEGATIVE,我必须使用BUTTON1BUTTON2

试试这个:

AlertDialog.Builder builder = new AlertDialog.Builder(this);


builder.setTitle("Confirm");
builder.setMessage("Are you sure?");


builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {


public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog


dialog.dismiss();
}
});


builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {


// Do nothing
dialog.dismiss();
}
});


AlertDialog alert = builder.create();
alert.show();

谢谢尼基,你的回答帮助我改善了现有的简单添加我想要的行动如下

AlertDialog.Builder builder = new AlertDialog.Builder(this);


builder.setTitle("Do this action");
builder.setMessage("do you want confirm this action?");


builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {


public void onClick(DialogInterface dialog, int which) {
// Do do my action here


dialog.dismiss();
}


});


builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
// I do not need any action here you might
dialog.dismiss();
}
});


AlertDialog alert = builder.create();
alert.show();

史蒂夫的回答是正确的,尽管有些片段过时了。下面是一个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并使用它来代替嵌入式侦听器。

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

问一个人他是否想打电话对话。

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;


public class Firstclass extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);


ImageView imageViewCall = (ImageView) findViewById(R.id.ring_mig);


imageViewCall.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v){
try{
showDialog("0728570527");
} catch (Exception e){
e.printStackTrace();
}
}
});
}


public void showDialog(final String phone) throws Exception {
AlertDialog.Builder builder = new AlertDialog.Builder(Firstclass.this);


builder.setMessage("Ring: " + phone);


builder.setPositiveButton("Ring", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){


Intent callIntent = new Intent(Intent.ACTION_DIAL);// (Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + phone));
startActivity(callIntent);


dialog.dismiss();
}
});


builder.setNegativeButton("Abort", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
dialog.dismiss();
}
});
builder.show();
}
}

这对我来说很管用:

AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());


builder.setTitle("Confirm");
builder.setMessage("Are you sure?");


builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {


public void onClick(DialogInterface dialog, int which) {


// Do nothing, but close the dialog
dialog.dismiss();
}
});


builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {


// Do nothing
dialog.dismiss();
}
});


AlertDialog alert = builder.create();
alert.show();

你可以为决策实现一个通用的解决方案,并在另一种情况下使用,而不仅仅是yes/no和自定义警报动画或布局:

像这样的东西;首先创建用于传输数据的类:

public class AlertDecision {


private String question = "";
private String strNegative = "";
private String strPositive = "";


public AlertDecision question(@NonNull String question) {
this.question = question;
return this;
}


public AlertDecision ansPositive(@NonNull String strPositive) {
this.strPositive = strPositive;
return this;
}


public AlertDecision ansNegative(@NonNull String strNegative) {
this.strNegative = strNegative;
return this;
}


public String getQuestion() {
return question;
}


public String getAnswerNegative() {
return strNegative;
}


public String getAnswerPositive() {
return strPositive;
}
}

后的接口,用于返回结果

public interface OnAlertDecisionClickListener {


/**
* Interface definition for a callback to be invoked when a view is clicked.
*
* @param dialog the dialog that was clicked
* @param object The object in the position of the view
*/
void onPositiveDecisionClick(DialogInterface dialog, Object object);
void onNegativeDecisionClick(DialogInterface dialog, Object object);
}

现在你可以很容易地创建一个utils(在这个类中,你可以为警报实现不同的动画或自定义布局):

public class AlertViewUtils {


public static void showAlertDecision(Context context,
@NonNull AlertDecision decision,
final OnAlertDecisionClickListener listener,
final Object object) {


AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(decision.getQuestion());
builder.setPositiveButton(decision.getAnswerPositive(),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listener.onPositiveDecisionClick(dialog, object);
}
});


builder.setNegativeButton(decision.getAnswerNegative(),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listener.onNegativeDecisionClick(dialog, object);
}
});


android.support.v7.app.AlertDialog dialog = builder.create();
dialog.show();
}
}

最后是活动或片段的召唤;你可以在你的案例或其他任务中使用这个:

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
initResources();
}


public void initResources() {
Button doSomething = (Button) findViewById(R.id.btn);
doSomething.setOnClickListener(getDecisionListener());
}


private View.OnClickListener getDecisionListener() {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDecision decision = new AlertDecision()
.question("question ...")
.ansNegative("negative action...")
.ansPositive("positive action... ");
AlertViewUtils.showAlertDecision(MainActivity.this,
decision, getOnDecisionListener(), v);
}
};
}


private OnAlertDecisionClickListener getOnDecisionListener() {
return new OnAlertDecisionClickListener() {
@Override
public void onPositiveDecisionClick(DialogInterface dialog, Object object) {


//do something like create, show views, etc...
}


@Override
public void onNegativeDecisionClick(DialogInterface dialog, Object object) {
//do something like delete, close session, etc ...
}
};
}
}

这里所有的答案都归结为冗长且不利于读者的代码:这正是提问者试图避免的。对我来说,最简单的方法是在这里使用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),但无论如何,它对编写更清晰的代码非常有帮助。

在芬兰湾的科特林:

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

显示对话框匿名作为命令链&没有定义其他对象:

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

1.创建AlertDialog,设置消息、标题和正面、负面按钮:

final AlertDialog alertDialog = new AlertDialog.Builder(this)
.setCancelable(false)
.setTitle("Confirmation")
.setMessage("Do you want to remove this Picture?")
.setPositiveButton("Yes",null)
.setNegativeButton("No",null)
.create();

2.现在在DialogInterface上找到两个按钮,然后单击setOnClickListener():

alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
Button yesButton = (alertDialog).getButton(android.app.AlertDialog.BUTTON_POSITIVE);
Button noButton = (alertDialog).getButton(android.app.AlertDialog.BUTTON_NEGATIVE);
yesButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Now Background Class To Update Operator State
alertDialog.dismiss();
Toast.makeText(GroundEditActivity.this, "Click on Yes", Toast.LENGTH_SHORT).show();
//Do Something here
}
});


noButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alertDialog.dismiss();
Toast.makeText(GroundEditActivity.this, "Click on No", Toast.LENGTH_SHORT).show();
//Do Some Thing Here
}
});
}
});

3.显示Alertdialog:

alertDialog.show();

注意:不要忘记AlertDialog的Final Keyword。

你可以在Kotlin中轻松完成:

 alert("Testing alerts") {
title = "Alert"
yesButton { toast("Yess!!!") }
noButton { }
}.show()

对于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()
}

芬兰湾的科特林的实现。

你可以像这样创建一个简单的函数:

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"
}
})