【问题标题】:Android ConstraintLayout width relative to item on the rightAndroid ConstraintLayout 相对于右侧项目的宽度
【发布时间】:2017-07-31 02:38:30
【问题描述】:

在 iOS 中,我可以在项目之间设置一个空格,在 Android 中如何实现?

例如:

我想在屏幕左侧有一个TextView,固定在父级的左边缘,在屏幕右侧有一个TextView,固定在父级的右边缘,两者都在同一行。

现在我希望左侧 TextView 的宽度尽可能宽,但左侧 TextView 和右侧 TextView 之间的最小间距为 16dp。

我希望它是可以理解的。

【问题讨论】:

  • 如果我明白你想要什么,你可以使用padding 来添加你需要的空间。如果你使用RelativeLayout作为父布局,你可以左右对齐TextView

标签: android constraints textview android-constraintlayout


【解决方案1】:

就在视图周围留出空间而言,您会考虑使用margin (see here for the difference between padding and margin in Android layouts)。

特别是在ConstraintLayout 中,它看起来像:

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

    <TextView
        android:id="@+id/left_text_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/right_text_view"
        android:layout_marginRight="16dp"
        android:text="left text" />

    <TextView
        android:id="@+id/right_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintRight_toRightOf="parent"
        android:text="right text" />

</android.support.constraint.ConstraintLayout>

注意 TextView 的宽度之间的差异。右边是wrap_content,所以它会改变它的大小以适应它的文本。左边的宽度为 0dp,在 ConstraintLayout 中表示“匹配约束”。它需要一个左右约束才能计算出宽度,所以我们都给出了。

我们还在第一个 TextView 的右侧添加了一个边距,以确保视图之间的间隙。或者,我们可以在第二个 TextView 上将 16dp 添加为 layout_marginLeft 或将其拆分为每个 8dp,具体取决于在这种情况下最有意义的情况。

【讨论】:

    【解决方案2】:

    如果我了解您想要什么,您可以使用paddingTextView 添加您需要的空间。如果你使用RelativeLayout作为父布局,你可以左右对齐TextView

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      • 2012-07-30
      • 2017-12-28
      • 1970-01-01
      • 1970-01-01
      • 2011-03-08
      • 1970-01-01
      相关资源
      最近更新 更多