如何使用"确定"按钮添加消息框?

Raj*_*ddy 78 android messagebox

我想显示一个带OK按钮的消息框.我使用了以下代码,但它导致带有参数的编译错误:

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();
Run Code Online (Sandbox Code Playgroud)

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

Par*_*ani 71

我认为你可能没有为ok正面按钮添加点击监听器的问题.

dlgAlert.setPositiveButton("Ok",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          //dismiss the dialog  
        }
    });
Run Code Online (Sandbox Code Playgroud)


Sur*_*gch 28

因为在您的情况下,您只想通过简短的消息通知用户,Toast这样可以提供更好的用户体验.

Toast.makeText(getApplicationContext(), "Data saved", Toast.LENGTH_LONG).show();
Run Code Online (Sandbox Code Playgroud)

更新:现在建议使用Snackbar而不是Toast for Material 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的活动中需要时调用它:

DialogFragment dialog = new MyDialogFragment();
dialog.show(getSupportFragmentManager(), "MyDialogFragmentTag");
Run Code Online (Sandbox Code Playgroud)

也可以看看

在此输入图像描述


Fer*_*anB 9

代码编译好我.可能是你忘了添加导入:

import android.app.AlertDialog;
Run Code Online (Sandbox Code Playgroud)

无论如何,你有一个很好的教程在这里.