如何使用 Constraint Layout 模拟带权重的 LinearLayout

14

如何在ConstraintLayout中像LinearLayout一样平均分配空间?
例如,如果使用约束条件来编写下面的布局,它会变成什么样子?

<LinearLayout 
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="horizontal">

  <TextView
    android:id="A"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1" />

  <TextView
    android:id="B"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1" />

  <TextView
    android:id="C"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1" />

  <TextView
    android:id="D"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1" />
</LinearLayout>
在 Constraint Layout 中,我可以将 AD 设置到边缘,A←B→D 使用33的偏移量并且 A←C→D 使用66的偏移量来使每个元素之间有大致相等的空间。但是这种解决方案并不真正可扩展。
在 Constraint Layout 中有没有更好的方法来实现这一点?

你真的需要直接将项目放在 ConstraintLayout 中吗?还是可以将它们放在 LinearLayout 中,然后再将 LinearLayout 放入 ConstraintLayout 中呢? - lionscribe
@lionscribe ConstraintLayout的出现是为了实现扁平化设计并提高性能等目的。因此,我正在寻找一种扁平化的方法来实现这一点,而不需要任何其他嵌套布局。 - oldergod
这里有新的文档,网址为https://developer.android.com/training/constraint-layout/index.html。 - James Moore
3个回答

25

请问您能否更新一下示例代码。我在Android Studio 2.2.2布局编辑器中找不到像添加垂直指南线和添加水平指南线这样的选项。 - ramji
@ramji,2.2.2 UI中没有此选项,您现在必须修改XML。您可以在https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html上查看Chains文档。 - Nicolas Roard

8
目前(约束布局alpha 6版),实现此功能的唯一方法是使用具有百分数位置的垂直指南线,然后对于每个小部件以这样的方式将它们限制在指南线上:
左侧 <- 小部件A -> 指南线1 <- 小部件B -> 指南线2 <- 小部件C -> 右侧
其中,指南线1为0.33,指南线2为0.66。
虽然可以实现此目的,但我认为相比使用线性布局来完成此特定任务,这种方法不会更快-如果您只想要这种确切的行为,请使用线性布局(甚至在约束布局内部)。使用约束布局的唯一优点是,您可以仅针对给定轴定义此行为,而另一个轴完全可以被限制得不同(而对于线性布局,则会对齐-但这是常见需求)。
尽管我们计划在未来版本的约束布局中使此特定行为变得更加容易,但这并不意味着所有现有布局都不再使用。

我使用了类似的方法,但正如你所知,它并不可扩展;如果添加/删除小部件,我们需要重新定义这些指南。无论如何,感谢你提醒我。 - oldergod
1
是的 - 这就是为什么我们计划在ConstraintLayout中添加另一种机制的原因。但在那种情况下使用线性布局也可以。 - Nicolas Roard

-2
例如:
<Button
    android:id="@+id/btn_a"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="ButtonA"
    app:layout_constraintHorizontal_chainStyle="spread"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toLeftOf="@+id/btn_b" />

<Button
    android:id="@+id/btn_b"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="ButtonB"
    app:layout_constraintLeft_toRightOf="@+id/btn_a"
    app:layout_constraintRight_toLeftOf="@+id/btn_c" />

<Button
    android:id="@+id/btn_c"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="ButtonC"
    app:layout_constraintLeft_toRightOf="@+id/btn_b"
    app:layout_constraintRight_toRightOf="parent" />


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