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

时间:2016-10-03 20:33:40

标签: android

我有一个对话框Fragment,我想把ok / cancel按钮放在对话框的底部。我试过,但我唯一得到的是编辑文本上的按钮(在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>

3 个答案:

答案 0 :(得分:5)

您将覆盖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();
}

答案 1 :(得分: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 .....

答案 2 :(得分:0)

几年前,我已经找到了解决方案,但是我无法再访问存储库,因此不得不再次发明轮子。

我希望DialogFragment具有生命周期访问权限,以便观察LiveData对象(通过viewLifeCyclerOwner)。 在布局中使用数据绑定。之所以使用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
            }
        }
    }
}