ConstraintLayout:如何让视图成为屏幕宽度的一半并居中?

新手上路,请多包涵

长话短说

视图宽度必须正好是屏幕的一半,并且居中。使用 ConstraintLayout

请注意,该视图没有任何内部宽度。

 <View android:background="#ff0000" ... />

原问题

我想实现一个布局,其中视图大小是屏幕大小的一半,并且水平居中。

像这样:|–view–|

我找不到任何使用 ConstraintLayout 的方法。我发现最好的是在分别位于最左和最右的 2 个假视图上使用 app:layout_constraintHorizontal_weight="1" ,在我的视图中使用 app:layout_constraintHorizontal_weight="1.5"

有什么更好的办法吗?

原文由 Softlion 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.4k
2 个回答

在测试版中,您可以使用百分比宽度。如果您不能使用测试版,您可以使用两条垂直参考线:一条在屏幕宽度的 25% 处,一条在屏幕宽度的 75% 处。宽度为 0dp 的视图将被限制在这两个准则之间。此设置将为您提供屏幕宽度为 12 且居中的视图。

以下 XML 演示了这两种方式;一个使用 ConstraintLayout beta 版本,第二个使用当前生产版本中可用的功能。

在此处输入图像描述XML布局

<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/activity_main_inference"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:id="@+id/viewTop"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:layout_marginTop="16dp"
        android:background="@android:color/darker_gray"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_default="percent"
        app:layout_constraintWidth_percent="0.5" />

    <android.support.constraint.Guideline
        android:id="@+id/guidelineLeft"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.25" />

    <View
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:layout_marginTop="16dp"
        android:background="@android:color/darker_gray"
        app:layout_constraintEnd_toStartOf="@id/guidelineRight"
        app:layout_constraintStart_toEndOf="@id/guidelineLeft"
        app:layout_constraintTop_toBottomOf="@id/viewTop" />

    <android.support.constraint.Guideline
        android:id="@+id/guidelineRight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.75" />

</android.support.constraint.ConstraintLayout>

原文由 Cheticamp 发布,翻译遵循 CC BY-SA 3.0 许可协议

从\*\* ConstraintLayout1.1.0-beta1** 开始,您可以使用 百分比 来定义 widths & heights

 android:layout_width="0dp"
app:layout_constraintWidth_default="percent"
app:layout_constraintWidth_percent=".4"

这会将 width 定义 为屏幕宽度的 40%。结合使用百分比和 指南,您可以创建任何您想要 的基于百分比的布局

原文由 shahid17june 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题