将“确定/取消”按钮添加到DialogFragment

4
我有一个对话框片段,我想把确定/取消按钮放在对话框的底部。我尝试过,但是我得到的唯一结果就是按钮在编辑文本上方(该文本位于DialogFragment中)。这是我的对话框: enter image description here 这是我的对话框代码:
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>

请展示XML布局文件。 - AAnkit
为什么不使用AlertDialog并调用类似于这样的内容: new AlertDialog.Builder().setPositiveButton("确定", listener).setNegativeButton("取消", ...),您还可以使用.setView添加自定义视图。 - Al Wld
3个回答

6

您需要覆盖onCreateDialog方法,并使用AlertDialog.Builder来设置Positive和Negative按钮,类似于以下示例:

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

谢谢,这样我可以得到按钮,但我的布局现在被覆盖了,就像这样:http://imgur.com/3KRfbuD - Cosimo Sguanci
使用layoutInflater和builder来填充你的布局。 - Aung Myo Linn
在我的情况下,我获得了这个变化:LayoutInflater inflater = getActivity().getLayoutInflater(); - Максим Фомичёв

0
如果您想使用自定义对话框视图,请使用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 .....

0

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

我想要一个具有生命周期访问权限的DialogFragment,以便通过viewLifeCyclerOwner观察LiveData对象。布局中使用数据绑定。由于我还希望Ok / Cancel按钮具有本地行为,因此使用了AlertDialog。

这个类被清理了一下。

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
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接