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

时间:2018-05-14 20:24:43

标签: xml android-constraintlayout

我试图让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>

但是,它只会导致:

Screenshot Of Emulator

我做错了什么?

1 个答案:

答案 0 :(得分:1)

如果您使用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>

这会产生:

This

更新

  1. 为什么将layout_width设置为0dp并使用start / end而不是layout:width =&#34; match_parent“?
  2. 好问题。 ConstraintLayout不支持match_parent(现在,一年后,我认为没问题的决定,因为它会强制用户在纠正时提出这个问题,但我认为这应该是一个警告,并且布局应该已经完成​​了预期 - 将每一方都固定到父级并在幕后使用0dp-)。在实践中它并不总是这样做,这比使用0dp的技术正确性更令人困惑(在幕后,它对应于MATCH_CONSTRAINT,而不是MATCH_PARENT)。我建议你偷看the official Constraint Layout docs来了解它。

    对于“Causal I'匆忙”读者,我使用了0dp因为`match_parent_不能像你想象的那样在ConstraintLayout上工作(它可能看起来不错但是它没有工作)。 0dp意味着匹配约束,你的大小最终将由此确定。

    为什么开始/结束?因为如果你的目标是API 16+,你不应该使用左/右,如果你的目标是API 16&lt;那么你应该同时使用,因为从左到右这很好,但是如果不使用开始/结束,阿拉伯语,希伯来语和许多右到右语言将无法正常工作。 (左边是右边,右边是左边!)。请相信我,对所有事情始终使用开始/结束。

    1. 如何查看我正在使用的约束库版本?
    2. 您的图书馆是通过Gradle导入的,因此请打开build.gradle并找到dependencies部分。它将包含与此类似的行:

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

      (例如)。没有神秘感。