16

I searched here on SO, on Google, on the android docs...

But I cannot find a single snippet of code with a example of custom viewgroup, I find at most some vague explanations...

Can someone provide one? How you make a viewgroup where you can put its children where you want?

1
  • PadLayout is a custom ViewGroup that lays out child views with equal distance.
    – Ali
    Commented Mar 11, 2020 at 19:05

2 Answers 2

16

I think the simplest example to look at is the source for AbsoluteLayout.java

https://github.com/android/platform_frameworks_base/blob/master/core/java/android/widget/AbsoluteLayout.java

You need to override onMeasure to measure the children and onLayout to position them.

I have strikingly more complicated ViewGroup code I can share as well if you want.

1
  • slund it would be nice if you can share ... can you specify the functions important to override for the child Commented Apr 10, 2012 at 11:23
-1

It't quite simple, all you need to do is to call super.onMeasure after calculate the exact dimentions of yout view.

class ProportionalConstraintLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
    
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {

        val exactWidth = 100 //do something to calculate the view widht
        val exactHeight = 100 //do something to calculate the view height

        setMeasuredDimension(exactWidth, exactHeight)
        super.onMeasure(
            MeasureSpec.makeMeasureSpec(exactWidth, MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(exactHeight, MeasureSpec.EXACTLY)
        )

    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.