How to make Constraint Layout Guideline in center

We can set a guideline using percentage by using the tag

app:layout_constraintGuide_percent="0.5"

where 0.5 (50%) being a float value between 0 to 1


Point to note is the guideline gets rendered erratically on the design screen . Using the app:layout_constraintGuide_percent="0.5" is enough to align it in the middle

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

In Kotlin:

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

Now you can update a ConstraintSet and connect to the guideline's id. For example, to have someView start 7dp to the right of center:

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

Where dpToPx is whatever your project uses to convert device units to pixels.