【问题标题】:How to dismiss AlertDialog.Builder?如何关闭 AlertDialog.Builder?
【发布时间】:2012-07-02 08:51:46
【问题描述】:

在下面的代码中,如何关闭警报框?我不想造成内存泄漏。我在alertDialog上尝试了.dismiss(),但是没有用... 谢谢

// User pressed the stop button
public void StopMsg_button_action(View view){
    final EditText password_input = new EditText(this); // create an text input field
    password_input.setHint("Enter Password"); // put a hint in it
    password_input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); // change it to password type

    AlertDialog.Builder alertDialog = new Builder(this); // create an alert box
    alertDialog.setTitle("Enter Password"); // set the title
    alertDialog.setView(password_input);  // insert the password text field in the alert box
    alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { // define the 'OK' button
        public void onClick(DialogInterface dialog, int which) {
             String entered_password = password_input.getText().toString();
             if (entered_password.equals(my_password)) {
                locManager.removeUpdates(locListener); // stop listening for GPS coordinates
                startActivity(new Intent(Emergency_1Activity.this,Main_MenuActivity.class)); // go to main menu
             } else {
                 alert("Incorrect Password");
             }
        } 
    });
    alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() { // define the 'Cancel' button
        public void onClick(DialogInterface dialog, int which) {

        } 
    });
    alertDialog.show(); // show the alert box
}

【问题讨论】:

    标签: android memory dialog alert dismiss


    【解决方案1】:

    dismiss() 有什么不好的地方?

    您应该可以使用Dialog.dismiss()Dialog.cancel()

    alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() { // define the 'Cancel' button
        public void onClick(DialogInterface dialog, int which) {
            //Either of the following two lines should work.
            dialog.cancel();
            //dialog.dismiss();
        } 
    });
    

    【讨论】:

    • AlertDialog.Builder 没有cancel 方法
    • @xmenW.K. cancel() 是 Dialog 本身的方法,而不是构建器。
    • 是的,但在您的代码中(也有问题)alertDialogBuilder。在onClick 中,您应该使用参数中的dialog
    • 哦,我现在明白了。谢谢=)
    • 很好的解决方案!转储问题。
    【解决方案2】:

    只需覆盖 create 方法并保存对话框实例。然后你可以调用dismiss

    @Override
    public AlertDialog create() {
        this.dialog = super.create();
        return this.dialog;
    }
    

    代码的某处:

    dialog.dismiss();
    

    【讨论】:

    • 这是唯一适合我的解决方案。我创建了一个从 AlertDialog.Builder 扩展的类。有了它,我可以创建自己的解除方法。
    【解决方案3】:

    如果您不想放置任何按钮并且有自定义布局,其中您说 textview 并且您想在单击该 textview 时关闭警报对话框,则必须使用这种方式:

    AlertDialog alertDialog = builder.show();
    

    然后检查

    if(alertDialog != null && alertDialog.isShowing()){
          alertDialog.dismiss();
    }
    

    如果您想在检查某些条件后在活动中的其他位置将其关闭,这也是如此。

    【讨论】:

    • 完美的最佳答案,有很好的解释
    • 是的,就是这样。为什么他们没有在 Builder 本身中包含 close 方法让我感到震惊……不是每个人都想使用默认按钮。对于自定义 AlertDialog,这是目前唯一的方法。谢谢
    【解决方案4】:

    使用以下代码,您可以显示一个 ListBox AlertDialog,当您按下某个项目时,您会关闭该对话框。代码顺序很重要。

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
    
    String names[] ={"A","B","C","D"};
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext,android.R.layout.simple_list_item_1,names);
    
    LayoutInflater inflater = getLayoutInflater();
    View convertView = (View)inflater.inflate(R.layout.list_layout, null);
    ListView lv = (ListView) convertView.findViewById(R.id.listView1);
    lv.setAdapter(adapter);
    alertDialog.setView(convertView);
    alertDialog.setTitle("List");
    final AlertDialog ad = alertDialog.show();
    
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            //Toast.makeText(mContext, position, Toast.LENGTH_LONG).show();
            ad.dismiss();
        }
    });
    

    【讨论】:

    • 完美!非常感谢!
    • 谢谢!这里的关键是关闭使用 alertDialog.show() 创建的对话框。从构建器创建一个对话框并在该对话框上调用dismiss不会关闭我们在调用show()时创建的同一个对话框。这个让我有点难过 =)
    【解决方案5】:

    此方法演示了所需的代码 .. 来自 Namrata 的早期答案

    @SuppressLint("InflateParams")
    private static void showDialog(Activity activity, int layoutId)
    {
        LayoutInflater inflater = activity.getLayoutInflater();
        View dialoglayout = inflater.inflate(layoutId, null);
    
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setView(dialoglayout);
    
        CustomDialog.doCustomLogic(activity, layoutId, dialoglayout);
    
        final AlertDialog alertDialog = builder.show();
    
        // caller assumes there will be a btn_close element present
        Button closeNowBtn = (Button) dialoglayout.findViewById(R.id.btn_close);
        closeNowBtn.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                alertDialog.dismiss();
            }
        });
    }
    

    【讨论】:

      【解决方案6】:

      代码很简单:

      final AlertDialog show = alertDialog.show();
      

      最后以按钮的动作为例:

      show.dismiss();
      

      例如使用自定义警报对话框:

      java代码,你可以创建一个Object AlertDialog:

      public class ViewAlertRating {
      
          Context context;
          public ViewAlertRating(Context context) {
              this.context = context;
          }
      
          public void showAlert(){
      
              AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
              LayoutInflater inflater = ((Activity) context).getLayoutInflater();
              View alertView = inflater.inflate(R.layout.layout_test, null);
              alertDialog.setView(alertView);
      
              final AlertDialog show = alertDialog.show();
      
              Button alertButton = (Button) alertView.findViewById(R.id.btn_test);
              alertButton.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                      show.dismiss();
                  }
              });
          }
      }
      

      代码 XML layout_test.xml

      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="wrap_content">
      
      
          <TextView
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:text="Valoración"
              android:id="@+id/text_test1"
              android:textSize="20sp"
              android:textColor="#ffffffff"
              android:layout_centerHorizontal="true"
              android:gravity="center_horizontal"
              android:textStyle="bold"
              android:paddingTop="10dp"
              android:paddingBottom="10dp"
              android:background="#ff37dabb"
              android:paddingLeft="20dp"
              android:paddingRight="20dp" />
      
      
          <LinearLayout
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:paddingLeft="20dp"
              android:paddingRight="20dp"
              android:layout_marginTop="15dp">
      
              <EditText
                  android:layout_width="match_parent"
                  android:layout_height="120dp"
                  android:id="@+id/edit_test"
                  android:hint="Descripción"
                  android:textColor="#aa000000"
                  android:paddingLeft="10dp"
                  android:paddingRight="10dp"
                  android:textColorHint="#aa72777a"
                  android:gravity="top" />
          </LinearLayout>
      
          <LinearLayout
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="center_horizontal"
              android:paddingTop="10dp"
              android:paddingLeft="15dp"
              android:paddingRight="15dp"
              android:paddingBottom="15dp" >
      
              <LinearLayout
                  android:orientation="horizontal"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent" >
      
                  <LinearLayout
                      android:orientation="horizontal"
                      android:layout_width="match_parent"
                      android:layout_height="match_parent"
                      android:weightSum="1.00"
                      android:gravity="right" >
      
                      <Button
                          android:layout_width="match_parent"
                          android:layout_height="wrap_content"
                          android:text="Enviar"
                          android:id="@+id/btn_test"
                          android:gravity="center_vertical|center_horizontal"
                          android:textColor="#ffffffff"
                          android:background="@drawable/btn_flat_blue_selector" />
                  </LinearLayout>
              </LinearLayout>
          </LinearLayout>
      </LinearLayout>
      

      最后,调用 Activity:

      ViewAlertRating alertRating = new ViewAlertRating(this);
      alertRating.showAlert();
      

      【讨论】:

      • 很好的解决方案。帮了我很多!
      • 我正在寻找的东西 :-)
      【解决方案7】:

      我试过这个并且成功了!

      .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialogInterface, int i) {
                     alertDialog.setCancelable(true);
                  }
              });
      

      【讨论】:

        【解决方案8】:

        关闭或取消AlertDialog.Builder

        dialog.setNegativeButton("إلغاء", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss()
            }
        });
        

        你必须在对话界面调用dismiss()

        【讨论】:

          【解决方案9】:

          一个完整的例子:

              AlertDialog.Builder builder = new AlertDialog.Builder(this);
              View view = getLayoutInflater().inflate(R.layout.dialog_layout,null);
              TextView tvcancel = (TextView)view.findViewById(R.id.tvcancel);
              TextView tvdisconnect = (TextView)view.findViewById(R.id.tvdisconnect);
              builder.setView(view);
              final AlertDialog ad = builder.show();
          
              tvdisconnect.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                      ad.dismiss();
                      stopVpn();
                  }
              });
          
              tvcancel.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                      ad.dismiss();
                  }
              });
          

          【讨论】:

            猜你喜欢
            • 2019-02-10
            • 2011-10-13
            • 2020-07-25
            • 1970-01-01
            • 1970-01-01
            • 2016-08-15
            • 1970-01-01
            • 2015-06-29
            • 1970-01-01
            相关资源
            最近更新 更多