是的,我知道这里有AlertDialog.Builder,但是我很震惊地知道在Android中显示对话框有多困难(至少对程序员不友好)。
我曾经是.NET开发人员,但我想知道以下Android是否等效?
if (MessageBox.Show("Sure?", "", MessageBoxButtons.YesNo) == DialogResult.Yes){
// Do something...
}
是的,我知道这里有AlertDialog.Builder,但是我很震惊地知道在Android中显示对话框有多困难(至少对程序员不友好)。
我曾经是.NET开发人员,但我想知道以下Android是否等效?
if (MessageBox.Show("Sure?", "", MessageBoxButtons.YesNo) == DialogResult.Yes){
// Do something...
}
Answers:
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()
来获取上下文。或者,您可以使用yourFragmentName.getActivity()
。
AlertDialog.Builder builder = new AlertDialog.Builder(getView().getContext());
尝试这个:
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();
The constructor AlertDialog.Builder(MainActivity.DrawerItemClickListener) is undefined
史蒂夫·哈(Steve H)的答案很明确,但是这里有更多信息:对话框按其工作方式工作的原因是因为Android中的对话框是异步的(显示对话框时执行不会停止)。因此,您必须使用回调来处理用户的选择。
请查看此问题,以更长时间地讨论Android和.NET(与对话框有关)之间的差异: 对话框/ AlertDialogs:如何在对话框启动时“阻止执行”(.NET样式)
这为我工作:
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();
询问某人是否要呼叫Dialog ..
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();
}
}
史蒂夫的答案是正确的,尽管已经过时了。这是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
并使用它而不是嵌入式侦听器。
谢谢nikki,您的回答仅通过添加所需的操作即可帮助我改善现有条件,如下所示
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();
以命令链的形式匿名显示对话框,而无需定义其他对象:
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();
这里的所有答案都归结为冗长且不便于读者阅读的代码:这正是询问者试图避免的内容。对我而言,最简单的方法是在此处使用lambda:
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),但是无论如何,这对于编写更简洁的代码很有帮助。
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的最终关键字。
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();
您可以为决策实施通用解决方案,并在其他情况下不仅用于是/否,还可以通过动画或布局自定义警报:
像这样的东西;首先创建用于传输数据的类:
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 ...
}
};
}
}
您可以在Kotlin中如此轻松地完成此操作:
alert("Testing alerts") {
title = "Alert"
yesButton { toast("Yess!!!") }
noButton { }
}.show()
对于Android中的Kotlin::
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()
}
Kotlin实施。
您可以创建一个简单的函数,如下所示:
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"
}
})