Home > Blockchain >  how to change a view height programmatically based on a layout height
how to change a view height programmatically based on a layout height

Time:12-10

I am working on an app, and I need to create a kind of gauge looking tile. So basically, I have created a simple xml file. with the layout I need, and all the views, like below:

<androidx.constraintlayout.widget.ConstraintLayout
        android:id="@ id/tile_layout"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_columnWeight="1"
        android:background="@color/transparent">

        <View
            android:id="@ id/gauge"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="invisible"/>
...

the, in the fragment, I am doing:

        val layout: ConstraintLayout = view.findViewById(R.id.tile_layout)
        val gauge = view.findViewById<View>(R.id.gauge)
        val ratio = 75


        view.layoutParams = getParams()
        val newParams: ViewGroup.LayoutParams = gauge.layoutParams
        newParams.height = (layout.height * ratio / 100)
        gauge.setLayoutParams(newParams)

it's not working the height is still the same. I am looking to have the gauge view height about 75% of the layout height.

Any idea how ?

CodePudding user response:

I think you need to get the height when the layout is completely created by adding a OnGlobalLayoutListener; then use the layout.measuredHeight instead of layout.height:

val layout: ConstraintLayout = view.findViewById(R.id.tile_layout)
val gauge = view.findViewById<View>(R.id.gauge)

layout.viewTreeObserver.addOnGlobalLayoutListener(object :
    ViewTreeObserver.OnGlobalLayoutListener {
    override fun onGlobalLayout() {

        val ratio = 75
        view.layoutParams = getParams()
        val newParams: ViewGroup.LayoutParams = gauge.layoutParams
        newParams.height = (layout.measuredHeight * ratio / 100)
        gauge.layoutParams = newParams
        layout.viewTreeObserver.removeOnGlobalLayoutListener(this)
    }

})

CodePudding user response:

What Zain says may be correct, but you don't show enough code to know if that is true or not. I will say that your gauge view does not have constraints set and constraints are something that every direct child of ConstraintLayout should have and, for which, match_parent is invalid. See the documentation for ConstraintLayout.

Important: MATCH_PARENT is not recommended for widgets contained in a ConstraintLayout. Similar behavior can be defined by using MATCH_CONSTRAINT with the corresponding left/right or top/bottom constraints being set to "parent".

  • Related