【问题标题】:DialogFragment too wide and can't center itDialogFragment 太宽,无法居中
【发布时间】:2019-06-14 10:15:23
【问题描述】:

我已经尝试 google 很长一段时间了,但似乎没有一个答案对我有用。我在新片段中有 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 包装到 RelativeLayout 中,弄乱了 LayoutParams 和 StackOverflow 中的多个其他解决方案。我错过了什么?

【问题讨论】:

  • 你可以在线性布局中发布你的代码
  • 如果您觉得我的回答有帮助,请投赞成票

标签: android android-alertdialog android-dialogfragment android-dialog dialogfragment


【解决方案1】:

尝试将 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>

【讨论】:

    【解决方案2】:

    你必须设置android:gravity="center"android:layout_width="match_parent" 在您的线性布局根元素中以使根元素内的所有元素居中

    【讨论】:

      猜你喜欢
      • 2012-07-21
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 2014-11-30
      • 2021-07-11
      • 1970-01-01
      相关资源
      最近更新 更多