Ad

DialogFragment Too Wide And Can't Center It

I've tried to google for quite some time and none of the answers seem to work for me. I have AlertDialog in new fragment and no matter what I do it just won't center itself. I feel like I'm missing something basic, like inflating the view in wrong way something.

Here's what it looks like now: AlertDialog not centered

I want the views to be centered and not on the left side. Stripping the extra white space would be nice as well but not necessary, as long as the buttons are centered.

Here's what my code looks like:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
>

   <!--Row 1. (colors 1-4)-->
   <LinearLayout...>

   <!--Row 2. (colors 5-8)-->
   <LinearLayout...>

   <!--Row 3. (colors 9-12)-->
   <LinearLayout...>

</LinearLayout>

and

public class dialog_ThemePicker extends DialogFragment implements View.OnClickListener {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_themepicker, null);

    ...

    AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
    alertDialog.setTitle(R.string.dialog_theme_title);
    alertDialog.setView(view);
    alertDialog.show();

    return alertDialog;
}

I've tried to wrap the whole XML into RelativeLayout, mess with LayoutParams and multiple other solutions from StackOverflow. What am I missing?

Ad

Answer

Try to give match_parent to your rootLayout width then give center option to gravity Here is how it should be.

<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|center_vertical">


  <!--Row 1. (colors 1-4)-->
   <LinearLayout...>

   <!--Row 2. (colors 5-8)-->
   <LinearLayout...>

   <!--Row 3. (colors 9-12)-->
   <LinearLayout...>

</LinearLayout>
Ad
source: stackoverflow.com
Ad