Adding positive / negative Button to DialogFragment's Dialog

前端 未结 5 528
迷失自我
迷失自我 2020-12-08 13:15

I\'ve already written a DialogFragment. Now I\'ve realized that I want it to have a positive and a negative button just like an AlertDialog. How can I achieve such a thing w

5条回答
  •  余生分开走
    2020-12-08 13:55

    This is a bit old but lately I've been overriding onCreateView when extending AppCompatDialogFragment. Just put your own buttons in the same layout you return in onCreateView - use styles like @style/Widget.AppCompat.Button.Borderless.

    You get the added bonus of controlling the Dialog self-dismissing when an action button is clicked, especially since these custom views sometimes have required inputs and you want to block the auto-close of the Dialog when a button is clicked.

    Using a custom view in onCreateDialog has always felt dirty because you're inflating it with no container. Google tried making the API a bit nicer with the new v7 AlertDialog.Builder method setView(int layoutResId), but you can't call findViewById then.

    You should be adding a Theme like this in your styles.xml:

    
    

    You must override onCreateDialog in your DialogFragment to return new AppCompatDialog(getActivity(), R.style.AlertDialog) as well.

提交回复
热议问题