我有一个按钮,我想在按下时打开一个对话框。这是我的代码:
Button more = (Button) findViewById(R.id.more);
more.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Intent myIntent = new Intent(view.getContext(), agones.class);
//startActivityForResult(myIntent, 0);
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("hi");
alertDialog.setMessage("this is my app");
alertDialog.setButton("Continue..", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
}
});发布于 2011-01-31 19:52:42
正如@Roflcoptr所说,您还没有调用alertDialog.show()方法。这样你的对话框就不会出现了。
这是你编辑过的代码:
Button more = (Button) findViewById(R.id.more);
more.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Intent myIntent = new Intent(view.getContext(), agones.class);
//startActivityForResult(myIntent, 0);
AlertDialog alertDialog = new AlertDialog.Builder(<YourActivityName>this).create(); //Read Update
alertDialog.setTitle("hi");
alertDialog.setMessage("this is my app");
alertDialog.setButton("Continue..", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.show(); //<-- See This!
}
});如果你写的是this而不是<ActivityName>.this,那么它将引用View.OnClickListener,因为this当前正在它内部被访问。您需要在那里提供您的活动的名称。
发布于 2011-01-31 19:50:13
您的对话框不会显示,因为您没有调用AlertDialog#show。
发布于 2020-06-14 18:58:12
Aman Alam's souliton是好的,但是.setButton()部分给了我一个错误。所以我用kotlin实现了它,并修复了这个错误。
Kotlin
val dialog = AlertDialog.Builder(this)
dialog.setTitle("Title")
.setMessage("Write your message here.")
.setPositiveButton("YES") { dialog, whichButton ->
// DO YOUR STAFF
}
.setNegativeButton("NO") { dialog, whichButton ->
// DO YOUR STAFF
// dialog.close()
}
dialog.show()

有关对话框的更多信息:https://developer.android.com/guide/topics/ui/dialogs
https://stackoverflow.com/questions/4850493
复制相似问题