如何添加消息框’确定’按钮?

我想显示一个带“确定”按钮的消息框。我使用了下面的代码,但是它导致了一个带参数的编译错误:

AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
dlgAlert.setMessage("This is an alert with no consequence");
dlgAlert.setTitle("App Title");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();

我应该如何在 Android 中显示消息框?

222361 次浏览

代码编译对我来说没问题。也许你忘了添加导入:

import android.app.AlertDialog;

无论如何,你有一个很好的教程 给你

我认为可能有问题,你没有添加点击监听确定积极按钮。

dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
@Override
protected Dialog onCreateDialog(int id)
{
switch(id)
{
case 0:
{
return new AlertDialog.Builder(this)
.setMessage("text here")
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface arg0, int arg1)
{
try
{


}//end try
catch(Exception e)
{
Toast.makeText(getBaseContext(),  "", Toast.LENGTH_LONG).show();
}//end catch
}//end onClick()
}).create();
}//end case
}//end switch
return null;
}//end onCreateDialog

因为在您的情况下,您只想用简短的消息通知用户,所以使用 Toast会带来更好的用户体验。

Toast.makeText(getApplicationContext(), "Data saved", Toast.LENGTH_LONG).show();

更新: 现在推荐使用 点心吧而不是 Toast for Materials Design 应用程序。

如果您有一个更长的消息,您想给读者时间阅读和理解,那么您应该使用 DialogFragment。(文件目前建议将 AlertDialog包装在一个片段中,而不是直接调用它。)

创建一个扩展 DialogFragment的类:

public class MyDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {


// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("App Title");
builder.setMessage("This is an alert with no consequence");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// You don't have to do anything here if you just
// want it dismissed when clicked
}
});


// Create the AlertDialog object and return it
return builder.create();
}
}

然后,当你在活动中需要它的时候,叫它:

DialogFragment dialog = new MyDialogFragment();
dialog.show(getSupportFragmentManager(), "MyDialogFragmentTag");

参见

enter image description here