Android约束布局的奇怪行为

4

我的constraint layout版本是1.0.0-alpha8。在我的布局中加入了一个工具栏后,工具栏的左右两侧都有空白,就像下面的图片一样:

enter image description here

这是我的工具栏代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/colorPrimary">


</android.support.v7.widget.Toolbar>

我已经按照以下方式将其包含在我的布局中:
<include
    layout="@layout/toolbar_top"
    android:id="@+id/topPanel"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"/>

我在布局文件的根元素中没有使用任何额外的填充或边距。

另一件奇怪的事情是,如果我编译或构建程序,我的代码会自动更改,例如:

<include
    layout="@layout/toolbar_top"
    android:id="@+id/topPanel"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"/>

更改为

<include
    layout="@layout/toolbar_top"
    android:id="@+id/topPanel"
    android:layout_height="wrap_content"
    android:layout_width="368dp"/>

这个指南还增加了一些我没有写到的额外价值,例如自动添加layout_editor_absoluteX

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/guideline1"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.15"
    tools:layout_editor_absoluteX="58dp"/>

目标 SDK 和使用的主题是哪个? - Ankita Shah
@AnkitaShah 目标SDK版本为24,主题为Theme.AppCompat.Light.NoActionBar。 - Mithun Sarker Shuvro
尝试这个Toolbar parent = (Toolbar) customView.getParent(); parent.setPadding(0, 0, 0, 0); // 对于选项卡,否则在选项卡中给出空间 parent.setContentInsetsAbsolute(0, 0);或者查看这个 https://dev59.com/914c5IYBdhLWcg3w9-F2#28086802 - Ankita Shah
@AnkitaShah 我的问题是为什么在预览中显示这个并添加额外的代码。 - Mithun Sarker Shuvro
1个回答

14

首先,您应该更新到ConstraintLayout beta 4。

现在,您遇到的根本问题是在工具栏上使用了match_parent,这在ConstraintLayout中不受支持。您需要添加:

app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"

使用0dp代替match_parent:

<include
    layout="@layout/toolbar_top"
    android:id="@+id/topPanel"
    android:layout_height="wrap_content"
    android:layout_width="0dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"/>

请注意,您可以通过在组件上右键单击并选择image轻松创建这些属性。

在Android Studio 2.2中,您需要按住键才能创建约束条件,而在Android Studio 2.3中,默认情况下会创建约束条件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接