首页 > 解决方案 > DialogFragment 太宽,无法居中

问题描述

我已经尝试谷歌很长一段时间了,但似乎没有一个答案对我有用。我在新片段中有 AlertDialog,无论我做什么,它都不会居中。我觉得我缺少一些基本的东西,比如以错误的方式夸大视图。

这是它现在的样子: AlertDialog not centered

我希望视图居中而不是左侧。只要按钮居中,去除多余的空白也很好,但不是必需的。

这是我的代码的样子:

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

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

我试图将整个 XML 包装到RelativeLayoutLayoutParams 和 StackOverflow 中的多个其他解决方案中。我错过了什么?

标签: androidandroid-alertdialogandroid-dialogfragmentandroid-dialogdialogfragment

解决方案


尝试将 match_parent 赋予您的 rootLayout 宽度,然后赋予center重力选项这是应该的。

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

推荐阅读