Android 向DialogFragment添加确定/取消按钮

Android 向DialogFragment添加确定/取消按钮,android,Android,我有一个对话框片段,我想把ok/cancel按钮放在对话框的底部。我试过了,但唯一得到的是编辑文本上的按钮(在DialogFragment中)。这是我的对话: 这是我的对话代码: public class dialogNewFile extends DialogFragment { private EditText textNewFile; public dialogNewFile(){} public static dialogNewFile newIstance(String titl

我有一个对话框片段,我想把ok/cancel按钮放在对话框的底部。我试过了,但唯一得到的是编辑文本上的按钮(在DialogFragment中)。这是我的对话:

这是我的对话代码:

public class dialogNewFile extends DialogFragment {
private EditText textNewFile;

public dialogNewFile(){}

public static dialogNewFile newIstance(String title){
    dialogNewFile frag=new dialogNewFile();
    Bundle args=new Bundle();
    args.putString("title",title);
    frag.setArguments(args);
    return frag;
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedIstanceState ){
    return inflater.inflate(R.layout.fragment_newfile,container);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedIstanceState){
    super.onViewCreated(view, savedIstanceState);
    textNewFile=(EditText) view.findViewById(R.id.edit_text_newfile);
    String title=getArguments().getString("title","Enter name");
    getDialog().setTitle(title);
    textNewFile.requestFocus();
    getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}

@Override
public void onResume() {
    Window window = getDialog().getWindow();
    Point size = new Point();
    // Store dimensions of the screen in `size`
    Display display = window.getWindowManager().getDefaultDisplay();
    display.getSize(size);
    // Set the width of the dialog proportional to 75% of the screen width
    window.setLayout((int) (size.x * 0.75), (int) (size.x * 0.50));
    window.setGravity(Gravity.CENTER);
    // Call super onResume after sizing
    super.onResume();

}
这是对话框片段的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:id="@+id/dialogNewFile">

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="35dp"
    android:hint="@string/hint_new_file"
    android:inputType="text"
    android:id="@+id/edit_text_newfile"/>

</LinearLayout>

您应覆盖
onCreateDialog
并使用
AlertDialog.Builder
设置正按钮和负按钮,如下所示:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    String title = getArguments().getString("title");
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(title);
    builder.setMessage("Are you sure?");

    // Edited: Overriding onCreateView is not necessary in your case
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View newFileView = inflater.inflate(R.layout.fragment_newfile, null);
    builder.setView(newFileView);

    builder.setPositiveButton("OK",  new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // on success
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    return builder.create();
}

如果要使用自定义对话框视图,请使用alertdialog.setView方法

       AlertDialog.Builder builder = new AlertDialog.Builder(this); 
       View myview = alertDialog.getLayoutInflater().inflate(R.layout.custom_dialog_layout, null);
       final AlertDialog alertDialog = builder.create();
       builder.setView(myview);
       alertDialog .show();
对于单击事件

Button positiveButton = myview.findViewById(R.id.btnPositive);
positiveButton.setOnclickListener(new OnClickListener .....

我在几年前就找到了解决方案,但我再也无法访问存储库了,所以我不得不再次发明轮子

我想要使用lifecycle access查看一个LiveData对象(通过
viewLifeCyclerOwner
)。 布局中使用了数据绑定。之所以使用AlertDialog,是因为我还希望Ok/Cancel按钮使其具有本机行为

全班都打扫了一下

class AddDiscountCodeDialog : DialogFragment(), DialogInterface.OnShowListener {
    private lateinit var binding: DialogAddDiscountCodeBinding
    private lateinit var handler: AddDiscountCodeHandler

    // Full screen dialogs are ugly
    override fun onResume() {
        super.onResume()

        val params = dialog?.window?.attributes
        params?.width = WindowManager.LayoutParams.MATCH_PARENT
        params?.height = WindowManager.LayoutParams.WRAP_CONTENT
        dialog?.window?.attributes = params as WindowManager.LayoutParams
    }

    // Override this method to initialize viewLifecycleOwner
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return binding.root
    }

    // Create a custom dialog.
    // Binding class is instantiated here because we need to set the view
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        binding = DialogAddDiscountCodeBinding.inflate(layoutInflater)

        val alert = AlertDialog.Builder(requireContext())
                .setTitle("Title")
                .setPositiveButton("Ok Button", null)
                .setNegativeButton("Cancel", null)
                .setView(binding.root)
                .create()
                .also {
                    it.setOnShowListener(this)
                    it.setCanceledOnTouchOutside(false)
                }

        return alert
    }

    // Overwrite the positive button click so it won't dismiss when clicked
    override fun onShow(dialog: DialogInterface?) {
        val button: Button = (dialog as AlertDialog).getButton(AlertDialog.BUTTON_POSITIVE)
        button.setOnClickListener {
            setLoading(true)

            val code = binding.code
            handler.addDiscountCode(code.toString()).observe(viewLifecycleOwner, Observer { result ->
                setLoading(false)

                // ... removed code

                dismiss()
            })
        }
    }

    // Set loading state in the layout. Blocks the "Positive" button to avoid multiple API calls.
    private fun setLoading(loading: Boolean) {
        val button: Button? = (dialog as? AlertDialog)?.getButton(AlertDialog.BUTTON_POSITIVE)

        button?.isEnabled = !loading
        button?.alpha = if (loading) 0.5f else 1.0f
        binding.loading = loading
    }

    companion object {
        val TAG = AddDiscountCodeDialog::class.java.simpleName

        fun create(handler: AddDiscountCodeHandler): AddDiscountCodeDialog {
            return AddDiscountCodeDialog().also {
                it.handler = handler
            }
        }
    }
}

向我们展示xml布局文件。为什么不使用AlertDialog并调用如下内容:new AlertDialog.Builder().setPositiveButton(“确定”,侦听器)。setNegativeButton(“取消”),您也可以使用.SetViewThank添加自定义视图。谢谢,这样我可以获得按钮,但我的布局现在已包括在内,如下所示:使用layoutInflater使用生成器对布局进行充气。在我的情况下,我获得了以下更改:layoutInflater充气器=getActivity().getLayoutInflater();