无法在片段内创建对话框

时间:2021-07-09 22:01:12

标签: android-studio dialog fragment

我正在尝试在片段中创建一个对话框。当我尝试按下按钮并进入应用程序折叠的对话框时。 我猜代码不对,你能帮我解决这个问题吗?

这是我的代码:

 private void openDialog(){


      Dialog dialog=new Dialog(getContext());
     //AlertDialog.Builder builder=new AlertDialog.Builder(getContext());

    LayoutInflater layoutInflater=this.getLayoutInflater();
        View custom_dialog=getActivity().getLayoutInflater().inflate(R.layout.geo_dialog,null);

     dialog.setContentView(custom_dialog);
    //   add_geofence_radius= custom_dialog.findViewById(R.id.radius_size);
        save_btn=custom_dialog.findViewById(R.id.save_btn);
        cancel_btn=custom_dialog.findViewById(R.id.cancel_btn);
      /*  save_btn.setOnClickListener(new View.OnClickListener() {
            @Override



            }
        });


       */
        /*cancel_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });

         */

   //    dialog.setTitle("hello");
     dialog.show();

    }

1 个答案:

答案 0 :(得分:1)

在 android 中显示对话框的最佳方式是使用“DialogFragments”,因为它们知道它所附加的视图(即片段/活动)的生命周期

以下是 Android 文档中提供的示例:

public class PurchaseConfirmationDialogFragment extends DialogFragment {
       @NonNull
       @Override
       public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
              return new AlertDialog.Builder(requireContext())
                    .setMessage(getString(R.string.order_confirmation))
                    .setPositiveButton(getString(R.string.ok), (dialog, which)    -> {} )
           .create();
       }

       public static String TAG = "PurchaseConfirmationDialog";
}

要显示对话框使用:

new PurchaseConfirmationDialogFragment().show(
   getChildFragmentManager(), PurchaseConfirmationDialog.TAG);

有关 dialogFragments 的更多参考,请查看:Create a DialogFragment

相关问题