从OnClick中关闭AlertDialog.Builder

时间:2011-07-26 20:29:24

标签: android alertdialog dismiss

我正在试图让它为用户弹出一个对话框,其中包含两个按钮,底部有一个取消按钮。当用户单击两个按钮之一时,对话框将消失,点击取消将仅取消对话框。取消部分工作正常,但我无法弄清楚如何手动关闭对话框。这是我的代码:

public void onItemClick(AdapterView<?> parent, View view,
                    final int position, long id) {

                Context mContext = getApplicationContext();
                LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
                View layout = inflater.inflate(R.layout.config_dialog,
                        (ViewGroup) findViewById(R.id.config_dialog));

                Button connect = (Button) layout.findViewById(R.id.config_connect);
                Button delete = (Button) layout.findViewById(R.id.config_delete);

                alert = new AlertDialog.Builder(Configuration.this);
                alert.setTitle("Profile");

                connect.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        trace("Connect" + Integer.toString(position));
                        toast("Connected");
                        SharedPreferences app_preferences = 
                                PreferenceManager.getDefaultSharedPreferences(Configuration.this);
                        SharedPreferences.Editor editor = app_preferences.edit();
                        editor.putString("IP", fetch.get(position).IP);
                        editor.commit();
                        //Add dismiss here


                    }

                });

                delete.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View v) {

                        trace("Delete");

                    }

                });


                // Set layout 
                alert.setView(layout);

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

                alert.show();

当我尝试添加alert.dismiss()时,Eclipse给了我一个错误。 .dismiss()也不会出现在alert的自动完成列表中。

4 个答案:

答案 0 :(得分:38)

Merlin的回答是正确的,应该被接受,但为了完整起见,我会发布一个替代方案。

问题是您正在尝试解除AlertDialog.Builder的实例而不是AlertDialog。这就是为什么Eclipse不会为您自动完成该方法的原因。一旦在AlertDialog.Builder上调用create(),就可以忽略因此而收到的AlertDialog。

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();
    }
}

答案 1 :(得分:20)

AlertDialog.Builder最适合用于小型简单对话框而非自定义对话框。

处理自定义对话框的最简洁方法是将AlertDialog子类化为上下文中的私有静态类(在本例中为您的活动)。

这是一个简化的例子:

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();
                }
            });
        }

    }
}

答案 2 :(得分:7)

代码非常简单:

final AlertDialog show = alertDialog.show();

最后在按钮的操作中例如:

show.dismiss();

例如使用自定义alertdialog:

enter image description here

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();

答案 3 :(得分:0)

无需创建自定义类。只需创建一个对话框的外部引用,并使用它来显示/解除。

这是一个使用Builder创建带有许多按钮的自定义对话框的示例:

在你的班级中声明:

private AlertDialog myDialog;

在onCreate()中,设置希望显示对话框的时间。就我而言,我有一个按钮:

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();
                }
            });
        }

以下是它的外观: enter image description here