Dismiss AlertDialog.Builder from OnClick

戏子无情 提交于 2019-12-03 03:06:21

AlertDialog.Builder is best suited for small simple dialog boxes rather than custom dialogs.

The cleanest way to handle custom dialogs is to subclass AlertDialog as a private static class in your context (in this case your activity).

Here is a simplified example:

public class AlertDialogTestActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        AlertDialog alert = new myCustomAlertDialog(this);
        alert.show();

    }

    private static class myCustomAlertDialog extends AlertDialog {

        protected myCustomAlertDialog(Context context) {
            super(context);

            setTitle("Profile");

            Button connect = new Button(getContext());
            setView(connect);
            connect.setText("Don't push me");
            connect.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    // I want the dialog to close at this point
                    dismiss();
                }
            });
        }

    }
}

Merlin's answer is correct and should be accepted, but for the sake of completeness I will post an alternative.

The problem is that you are trying to dismiss an instance of AlertDialog.Builder instead of AlertDialog. This is why Eclipse will not auto-complete the method for you. Once you call create() on the AlertDialog.Builder, you can dismiss the AlertDialog that you receive as a result.

public class AlertDialogTestActivity extends Activity
{

    AlertDialog alert;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button connect = new Button(this);
        connect.setText("Don't push me");

        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle("Profile");
        alertBuilder.setView(connect);


        connect.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                alert.dismiss();
            }
        });

        alert = alertBuilder.create();
    }
}

The code is very simple:

final AlertDialog show = alertDialog.show();

finally in the action of button for example:

show.dismiss();

For example with a custom alertdialog:

Code on java, you could create a 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();
            }
        });
    }
}

Code example 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>

finally, call on Activity:

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

There's no need to create a custom class. Just create an external reference to your Dialog and use it to show/dismiss.

Here's an example where I use Builder to create a custom Dialog with many buttons:

Declare it within you class:

private AlertDialog myDialog;

In your onCreate(), set when you want your Dialog to show up. In my case, I have a button:

addPhotoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("Select an option");
            builder.setItems(new CharSequence[]
                            {"Take a picture", "Choose from library", "Another button"},
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            switch (which) {
                                case 0:
                                    Toast.makeText(context, "Call camera", Toast.LENGTH_SHORT).show();
                                    break;
                                case 1:
                                    Toast.makeText(context, "Choose from library", Toast.LENGTH_SHORT).show();
                                    break;
                                case 2:
                                    Toast.makeText(context, "Another button", Toast.LENGTH_SHORT).show();
                                    break;
                            }
                        }
                    });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    addPhotoDialog.dismiss(); // Here I dismiss the Dialog even though it hasn't been created yet
                }
            });
            handler.post(new Runnable() {
                @Override
                public void run() {
                    addPhotoDialog = builder.create(); // Creates the Dialog just before showing it
                    addPhotoDialog.show();
                }
            });
        }

And here's how it looks:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!