I made a custom ViewGroup which has one child view. I want this child view height to be calculated based on the custom ViewGroup height. As far as I know the best place to detect the ViewGroup size is onSizeChanged callback so I put there a code responsible for changing child view size. Unfortunately, this doesn't work. Nothing changes.
class CustomViewGroup(context: Context, attrs: AttributeSet?) : ConstraintLayout(context, attrs) {
private val imageView = ImageView(context).apply {
id = ViewCompat.generateViewId()
setImageDrawable(ColorDrawable(Color.BLUE))
layoutParams = LayoutParams(100, 100)
}
init {
addView(imageView)
with(ConstraintSet()) {
clone(this@CustomViewGroup)
connect(imageView.id, ConstraintSet.START, id, ConstraintSet.START)
connect(imageView.id, ConstraintSet.TOP, id, ConstraintSet.TOP)
connect(imageView.id, ConstraintSet.END, id, ConstraintSet.END)
connect(imageView.id, ConstraintSet.BOTTOM, id, ConstraintSet.BOTTOM)
applyTo(this@CustomViewGroup)
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
imageView.updateLayoutParams { height = h / 4 } //some complex equation
}
}
<com.example.customviewgroup1.CustomViewGroup
android:id="@+id/customViewGroup"
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="@color/black"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />