Android 约束布局 - 使视图占据屏幕的上半部分

Android Constraint Layout - Make View Occupy Top Half of Screen

我正在尝试让 textview 占据屏幕的上半部分,这样我就可以熟悉新的约束布局系统。

我尝试使用以下方法:

<?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="match_parent"
    android:layout_height="match_parent"
    app:layout_constraintVertical_weight="2"
    tools:context=".MainActivity">

    <TextView
        android:text="Test"
        android:background="@color/colorPrimaryDark"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintLeft_toRightOf="parent"
        app:layout_constraintRight_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_weight="1" />

</android.support.constraint.ConstraintLayout>

但是,结果是这样的:

我做错了什么?

如果您使用 Constraint Layout 1.1.0(撰写本文时最新的稳定版)……最好的方法就是使用百分比!

<?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"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@android:color/black"
        android:text="Test"
        android:textColor="@android:color/white"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_default="percent"
        app:layout_constraintHeight_percent="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

这会产生:

更新

  1. 为什么将 layout_width 设置为 0dp 并使用 start/end 而不是 layout:width="match_parent”?

好问题。 ConstraintLayout doesn't support match_parent(一个决定现在,一年多后,我认为是可以的,因为它迫使用户在更正时问这个问题,但我认为它应该是一个警告和布局应该完成预期的工作 - 将每一侧固定到父级并在幕后使用 0dp -)。实际上,它并不总是这样做,这比使用 0dp 的技术正确性更令人困惑(在幕后,它对应于 MATCH_CONSTRAINT,而不是 MATCH_PARENT)。我建议您查看 the official Constraint Layout docs 以了解相关信息。

对于“因为我很着急”reader,我使用了 0dp,因为`match_parent_ 在 ConstraintLayout 上并不像您认为的那样起作用(它 可能看起来不错 但它不起作用)。 0dp 意味着匹配约束,你的大小将最终由它决定。

为什么 Start/End?因为你不应该使用 left/right 如果你的目标是 API 16+ 并且如果你的目标是 API 16< 那么你应该同时使用,因为从左到右这很好,但是阿拉伯语,如果您不使用 start/end,希伯来语和许多从右到左的语言将无法正常工作。 (左是右,右是左!)。相信我,永远使用 start/end 做任何事情。

  1. 如何检查我使用的约束库的版本?

您的库是通过 Gradle 导入的,因此打开您的 build.gradle 并找到 dependencies 部分。它将包含类似于以下的行:

implementation "com.android.support.constraint:constraint-layout:1.1.0”

(例如)。不神秘。