I have to build a more complex custom view in Android. The final layout should look like this:
<RelativeLayout>
<SomeView />
<SomeOtherView />
<!-- maybe more layout stuff here later -->
<LinearLayout>
<!-- the children -->
</LinearLayout>
</RelativeLayout>
However, in the XML files I just want do define this (without defining SomeView, SomeOtherView etc.):
<MyCustomView>
<!-- the children -->
</MyCustomView>
Is this possible in Android, and if yes: What would be the cleanest way to do it?
The possible solutions that came to my mind were ‘override the addView() methods’ and ‘remove all views and add them again later’, but I am unsure which way to go…
Thanks a lot in advance for your help! 🙂
It’s absolutely possible, and encouraged, to create custom container views. This is what Android would call a compound control. So:
You can override as many versions of
addView()as you feel are necessary, but in the end they all call back to the version I placed in the sample. Overriding just this method will have the framework pass all children found inside its XML tag to a specific child container.And then modify the XML as such:
res/layout/custom_layout.xml
The reason for using
<merge>is to simplify the hierarchy. All the child views will get attached to your custom class, which is aRelativeLayout. If you don’t use<merge>, you end up with aRelativeLayoutattached to anotherRelativeLayoutattached to all the children, which can cause issues.Kotlin version: