Header Ads

Center DialogFragment with padding

How do you center the DialogFragment in Android with padding on the right and left? Something like this

For the following, the code is at Github Gist

The problem:
When I created a DialogFragment, the layout's width (match_parent) is being ignored.
The solution for this is to get the window and set the width on the layout
@Override
public void onStart() {
super.onStart();
getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}

However we want to add padding on the right and left of the window.
One solution, which I did right now is to

Create the dialog with custom style
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final View view = View.inflate(getActivity(), R.layout.dialog_fragment, null);

Dialog dialog = new Dialog(getActivity(), R.style.DialogFragment);
dialog.setContentView(view);
return dialog;
}

On DialogFragment we extend it to the framework's Dialog style and set windowIsFloating to true with windowBackground of transparent
<style name="DialogFragment" parent="android:style/Theme.Dialog">
<item name="android:windowBackground">@android:color/transparent
<item name="android:windowNoTitle">true
<item name="android:windowIsFloating">true

<item name="android:layout_gravity">center
</style>
Add another layer on the layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:paddingRight="20dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/dialog_fragment_bg"
>
...

We added another layer so that we can add the simulated window style on the child layout, we also added a fake shadow on dialog_fragment_bg because we removed it when we set the windowBackground to transparent.

If there is a better solution, please comment below
Hope this helps :)

No comments:

Powered by Blogger.