最简单的是/否对话框片段

问题描述 投票:39回答:4

我想做一个dialog fragment问“你确定吗?”带有“是/否”回复。

我看过the documentation,它真的很冗长,遍布整个地方,解释了如何制作高级对话框,但没有完整的代码来制作一个简单的'hello world'类型的对话框。大多数教程都使用不推荐使用的对话框系统。 official blog似乎是不必要的复杂和难以理解。

那么,创建和显示真正基本的警报对话框的最简单方法是什么?如果它使用支持库,则奖励积分。

android dialog android-fragments android-alertdialog
4个回答
78
投票

DialogFragment实际上只是一个包装对话框的片段。您可以通过在DialogFragment的onCreateDialog()方法中创建和返回对话框来在其中放置任何类型的对话框。

下面是一个示例DialogFragment:

class MyDialogFragment extends DialogFragment{
    Context mContext;
    public MyDialogFragment() {
        mContext = getActivity();
    }
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
        alertDialogBuilder.setTitle("Really?");
        alertDialogBuilder.setMessage("Are you sure?");
        //null should be your on click listener
        alertDialogBuilder.setPositiveButton("OK", null);
        alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });


        return alertDialogBuilder.create();
    }
}

要创建对话框调用:

new MyDialogFragment().show(getFragmentManager(), "MyDialog");

并从某处解雇对话框:

((MyDialogFragment)getFragmentManager().findFragmentByTag("MyDialog")).getDialog().dismiss();

所有这些代码都可以与支持库完美配合,只需更改导入即可使用支持库类。


12
投票

那么,创建和显示真正基本的警报对话框的最简单方法是什么?如果它使用支持库,则奖励积分。

只需创建一个DialogFragment(SDK或支持库)并覆盖其onCreateDialog方法,以返回一个AlertDialog,其上设置了所需的文本和按钮:

public static class SimpleDialog extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(getActivity())
                .setMessage("Are you sure?")
                .setPositiveButton("Ok", null)
                .setNegativeButton("No way", null)
                .create();
    }

}

要在用户使用其中一个按钮时执行某些操作,您必须提供DialogInterface.OnClickListener的实例,而不是我的代码中的null引用。


5
投票

对于那些用Kotlin和Anko编码的人,你现在可以用4行代码做对话:

alert("Order", "Do you want to order this item?") {
    positiveButton("Yes") { processAnOrder() }
    negativeButton("No") { }
}.show()

3
投票

因为Activity / Fragment生命周期@athor和@lugsprog方法可能会失败,更优雅的方法是从方法onAttach获取活动上下文并将其存储为弱引用**(并尝试避免在DialogFragment中使用非默认构造函数!对话框使用参数的参数)像这样:

public class NotReadyDialogFragment extends DialogFragment {

    public static String DIALOG_ARGUMENTS = "not_ready_dialog_fragment_arguments";

    private WeakReference<Context> _contextRef;

    public NotReadyDialogFragment() {
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        /** example pulling of arguments */
        Bundle bundle = getArguments();
        if (bundle!=null) {
            bundle.get(DIALOG_ARGUMENTS);
        }

        //
        // Caution !!!
        // check we can use contex - by call to isAttached 
        // or by checking stored weak reference value itself is not null 
        // or stored in context -> example allowCreateDialog() 
        // - then for example you could throw illegal state exception or return null 
        //
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(_contextRef.get());
        alertDialogBuilder.setMessage("...");
        alertDialogBuilder.setNegativeButton("Przerwij", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        return alertDialogBuilder.create();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        _contextRef = new WeakReference<Context>(activity);
    }

     boolean allowCreateDialog() {
         return _contextRef !== null 
                && _contextRef.get() != null;
     }

编辑:&如果你想解雇对话,那么:

  1. 试着去做吧
  2. 检查它是否存在
  3. 检查它是否显示
  4. 解雇

这样的事情:

        NotReadyDialogFragment dialog = ((NotReadyDialogFragment) getActivity().getFragmentManager().findFragmentByTag("MyDialogTag"));
    if (dialog != null) {
        Dialog df = dialog.getDialog();
        if (df != null && df.isShowing()) {
            df.dismiss();
        }
    }

EDIT2:&如果你想将对话框设置为不可取消,你应该更改onCreatweDialog返回语句,如下所示:

    /** convert builder to dialog */
    AlertDialog alert = alertDialogBuilder.create();
    /** disable cancel outside touch */
    alert.setCanceledOnTouchOutside(false);
    /** disable cancel on press back button */
    setCancelable(false);

    return alert;
© www.soinside.com 2019 - 2024. All rights reserved.