如何在android中创建模态对话框

Jat*_*tel 15 android modal-dialog android-ui

我想为我的应用程序创建模态对话框.

所以当模态对话框打开时,其他活动被阻止.没有像后退按钮或按下主页按钮那样的事件.

并在该对话框取消和确定两个选项按钮.

谢谢...

Ye *_*ung 28

DialogsAndroid中有很多种.请看一下Dialogs.我想你想要的是什么AlertDialog.这是如何在BackPress按钮上实现的示例.

@Override
public void onBackPressed() {
    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle("Do you want to logout?");
    // alert.setMessage("Message");

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            //Your action here
        }
    });

    alert.setNegativeButton("Cancel",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            }
        });

    alert.show();

}
Run Code Online (Sandbox Code Playgroud)


小智 9

使用可以使用setCancellable(false); setCanceledOnTouchOutside(假); 对于对话框本身,应该停止该对话框从BACK关闭并通过点击对话框外部.

您无法覆盖HOME按钮.


Arm*_*ger 6

试试这个::

您需要创建要在弹出窗口中显示的布局.你可以创建布局XML并像这样使用它:

LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);  
            View layout = layoutInflater.inflate(R.layout.new_popup_layout, null);  
            final PopupWindow popupWindow = new PopupWindow(
                    layout, 
                       LayoutParams.WRAP_CONTENT,  
                             LayoutParams.WRAP_CONTENT);
Run Code Online (Sandbox Code Playgroud)

您还可以提供按钮的点击事件,如下所示:

ImageButton btnChoose = (ImageButton) layout.findViewById(R.id.btnChoose);
            btnChoose.setOnClickListener(new OnClickListener()  {

                @Override
                public void onClick(View v) {
}
});
Run Code Online (Sandbox Code Playgroud)

并显示这样的弹出窗口:在这里你想在按钮点击显示这个,然后按钮视图将在那里.

 popupWindow.showAtLocation(anyview,Gravity.CENTER, 0, 0);
Run Code Online (Sandbox Code Playgroud)


GrI*_*sHu 5

试试如下:

 AlertDialog.Builder builder = new AlertDialog.Builder(this);
 builder.setMessage("Are you sure you want to exit?")
  .setCancelable(false)
   .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int id) {
        MyActivity.this.finish();
   }
 })
 .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int id) {
        dialog.cancel();
   }
});
AlertDialog alert = builder.create();
Run Code Online (Sandbox Code Playgroud)

对于Home Key事件:

不,在Android中无法获取Home键事件.来自Home键代码的文档:http: //developer.android.com/reference/android/view/KeyEvent.html#KEYCODE_HOME

public static final int KEYCODE_HOME

密钥代码常量:Home键.此密钥由框架处理,永远不会传递给应用程序.