具有ConstraintLayout对话框宽度的AppCompatDialogFragment

时间:2016-10-20 10:02:58

标签: android android-constraintlayout appcompatdialogfragment

我试图将根布局的AppCompatDialogFragment作为ConstraintLayout。

根布局的layout_width设置为wrap_content。 但是当我执行代码时,即使内容发生变化,对话框也会收缩固定宽度。

这里是生成的布局代码

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                             xmlns:app="http://schemas.android.com/apk/res-auto"
                                             xmlns:tools="http://schemas.android.com/tools"
                                             android:layout_width="wrap_content"
                                             android:layout_height="wrap_content"
                                             android:orientation="vertical"
  >

  <TextView
    android:id="@+id/textView5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp"
    android:layout_marginEnd="16dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras tempus tristique ornare. Aenean ut magna in diam aliquet accumsan. "
    android:textSize="36sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>

这是我如何夸大布局:

View view = inflater.inflate(R.layout.weather_dialog, container, false);

Long text

Short text

我们可以看到,对于长文本,对话框会出现某种最大宽度&#34; (即使没有属性)。

我怎么能有一个对话框,在没有这个&#34;限制&#34;的情况下将其内容包装在宽度中?

1 个答案:

答案 0 :(得分:2)

有一对名为Windowandroid:windowMinWidthMajor的{​​{1}}个样式属性。

  

允许窗口沿屏幕的主要[次要]轴的最小宽度

(引自documentation

如果您通过定义某种风格

android:windowMinWidthMinor使用Theme
Dialog

并设置

<style name="FragmentDialogStyle" parent="Theme.AppCompat.Dialog">
    <item name="windowMinWidthMajor">@dimen/dialog_fragment_width</item>
    <item name="windowMinWidthMinor">@dimen/dialog_fragment_width</item>
    <item name="android:windowMinWidthMajor">@dimen/dialog_fragment_width</item>
    <item name="android:windowMinWidthMinor">@dimen/dialog_fragment_width</item>
</style>

在应用<item name="android:dialogTheme">@style/FragmentDialogStyle</item> <item name="dialogTheme">@style/FragmentDialogStyle</item> 中,Theme宽度将精确Dialog ,如果您还使用

dialog_fragment_width

使用android:layout_width="0dp"

然而,如果你继续使用

TextView

&#34;最大宽度&#34;你观察到会限制你的android:layout_width="wrap_content" 宽度。

顺便说一句,如果您为DialogTextView的背景着色,您会发现只有在使用ConstraintLayout宽度值时,所有边距都是正确的。

因此,似乎您最好的选择是为0dp设置android:layout_width="0dp",并为TextView提供不同的值,具体取决于当前屏幕(对于Nougat +:应用程序窗口)宽度。为此,您需要不同的目录,例如dialog_fragment_width

请注意:我使用模拟器测试运行Marshmallow的平板电脑和运行Lollipop的手机。虽然它有效,但如果我能解释原因,我会更开心。所以我认为这更像是答案,但我想分享我的观察结果。