【问题标题】:How to mimick Weighted LinearLayout with a Constraint Layout如何使用约束布局模仿加权线性布局
【发布时间】:2016-07-26 01:06:48
【问题描述】:

我们如何才能在约束布局中和在线性布局中一样节省空间?
比如下面的布局如果用约束写出来会变成什么样子?

<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>

在约束布局中,我可以将AD 设置为边缘,将A←B→D 设置为33 偏置,将A←C→D 设置为66 偏置,以使每个元素之间的空间相等。
但该解决方案并不能真正扩展。

在约束布局中是否有适当的方法来做到这一点?

【问题讨论】:

  • 你真的需要物品直接放在ConstraintLayout中,还是直接放到linearlayout中,然后把linearlayout放到ConstraintLayout中
  • @lionscribe ConstraintLayout 在这里,除其他外,进行平面设计并帮助提高性能。因此,我正在寻找一种以平面方式执行此操作的方法,无需任何其他嵌套布局。

标签: android android-layout android-constraintlayout


【解决方案1】:

仅供参考 -- Constraint Layout alpha 9 添加了 Chains,它允许您实现此行为。

【讨论】:

  • 能否请您更新任何示例代码。我无法在 Android Studio 2.2.2 布局编辑器中找到该选项,例如添加垂直指南和添加水平指南
  • @ramji 在 2.2.2 UI 中不可用,您现在必须修改 XML。您可以在 developer.android.com/reference/android/support/constraint/… 查看 Chains 文档
【解决方案2】:

目前(约束布局 alpha 6)唯一的其他选择是使用具有百分比位置的垂直准线,然后对于每个小部件将它们以如下方式约束到准线: 左侧 指南 1 指南 2 右侧

指南 1 为 0.33,指南 2 为 0.66。

但是。

虽然它有效,但我怀疑它会比使用线性布局更快地完成这个特定任务——如果你想要的只是这种确切的行为,只需使用线性布局(即使在约束布局内)。它为您提供约束布局的唯一优点是您可以仅为给定轴定义此行为,另一个轴可以完全不同地约束(而对于 LL,它将对齐 - 但这是共同的需要) .

虽然我们确实计划在未来版本的约束布局中使这种特定行为更容易实现,但这并不意味着不再使用所有现有布局。

【讨论】:

  • 我使用了类似的方法,但如您所知,它无法扩展;如果添加/删除小部件,我们需要重新定义这些准则。无论如何,感谢您的提醒。
  • 是的——这就是为什么我们计划在 ConstraintLayout 中为此添加另一种机制。但在这种情况下使用线性布局也很好。
【解决方案3】:

例如:

<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" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    相关资源
    最近更新 更多