如何在中心制作约束布局指南

How to make Constraint Layout Guideline in center

我有 3 条约束布局指南。左边有 16dp 左边距。第二个在右边,右边距 16dp但我想要另一个位于中心的指南。假设如果我从 Android Stdio XML 设计面板将此指南置于 nexus 5 的中心,那么在 nexus S 中它不会显示在中心。 如何解决?

 <android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.blabla.ScrollingActivity">

    <android.support.constraint.Guideline
        android:id="@+id/guideline_end"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_end="16dp" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="16dp" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline_center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="180dp"/>
 </android.support.constraint.ConstraintLayout>

我们可以使用标签

设置一个使用百分比的指南

app:layout_constraintGuide_percent="0.5"

其中 0.5 (50%) 是 0 到 1 之间的浮点值

在科特林中:

    // Create constraint layout (maybe you have this already)
    val buttonLayout = ConstraintLayout(context)
    buttonLayout.id = View.generateViewId()

    // Create guideline
    val centerGuideline = Guideline(context)
    centerGuideline.id = View.generateViewId()

    // We want a vertical guideline, 50% across the width
    val centerParams = ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.MATCH_PARENT)
    centerParams.guidePercent = 0.5f
    centerParams.orientation = ConstraintLayout.LayoutParams.VERTICAL

    // Add guideline to layout.
    buttonLayout.addView(centerGuideline, centerParams)

现在您可以将 ConstraintSetconnect 更新为指南的 ID。例如,要让 someView 从中心右侧开始 7dp:

    connect(someView.id, ConstraintSet.START, centerGuideline.id, ConstraintSet.START, dpToPx(context, 7))

其中 dpToPx 是您的项目用于将设备单位转换为像素的任何内容。

需要注意的是指南在设计屏幕上呈现不规律。使用 app:layout_constraintGuide_percent="0.5" 足以将其对齐在中间

<androidx.constraintlayout.widget.Guideline
app:layout_constraintGuide_percent="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>