Change in child view width or height breaks the parent view layout

  android, android-studio, java, kotlin, xml

There is a LinearLayout like the one below.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:animateLayoutChanges="true"
    android:id="@+id/linearLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

In this, I create and add a view as follows.

for (index in 0 until 3) {
    val width = if (index == 0) {
        60
    } else {
        16 
    }

    val params = LayoutParams(width, 12)
    params.marginStart = 12

    val view = View(context)
    view.layoutParams = params
    view.setBackgroundResource(R.drawable.light_bg)           

    linearLayout.addView(view, index)
}

It consists as follows;

enter image description here

To highlight the 2nd item, I do the following;

val firstView = linearLayout[0]
firstView.layoutParams.width = 16
firstView.layoutParams.height = 12
firstView.setBackgroundResource(R.drawable.light_bg)

val secondView = linearLayout[1]
secondView.layoutParams.width = 60
secondView.layoutParams.height = 12
secondView.setBackgroundResource(R.drawable.dark_bg)

and looks like the following;

enter image description here

To fix this, I try these in both streaming and runOnUiThread but still the result is the same.

linearLayout.requestLayout()
linearLayout.invalidate()
linearLayout.postInvalidate()

Anyone have any ideas?

Source: Android Questions

LEAVE A COMMENT