从 OnClick 中关闭 AlertDialog.Builder

发布于 2024-11-26 20:31:05 字数 2202 浏览 1 评论 0原文

我正在尝试为用户弹出一个对话框,该对话框的主体中有两个按钮,底部有一个取消按钮。当用户单击两个按钮之一时,对话框将消失,点击“取消”只会取消对话框。取消部分工作正常,但我不知道如何手动关闭对话框。这是我的代码:

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() 也不会出现在警报的自动完成列表中。

I'm trying to make it so that a dialog pops up for users which has two buttons in the body and a cancel button at the bottom. When a user clicks one of the two buttons the dialog will disappear, and hitting cancel will just cancel out of the dialog. The cancel part works fine, but I can't figure out how to dismiss the dialog manually. Here's my code:

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

When I try to add the alert.dismiss(), Eclipse gives me an error. .dismiss() also doesn't show up in alert's autocomplete list.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一念一轮回 2024-12-03 20:31:05

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

问题是您试图关闭 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();
    }
}

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();
    }
}
没企图 2024-12-03 20:31:05

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

    }
}

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

    }
}
风吹雪碎 2024-12-03 20:31:05

代码非常简单:

final AlertDialog show = alertDialog.show();

最后以按钮的操作为例:

show.dismiss();

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

在此处输入图像描述

Java代码,您可以创建一个对象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>

最后,调用关于活动:

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

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:

enter image description here

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();
岁月静好 2024-12-03 20:31:05

无需创建自定义类。只需创建对对话框的外部引用并使用它来显示/关闭。

下面是我使用 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();
                }
            });
        }

它的外观如下:
在此处输入图像描述

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:
enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文