简体   繁体   中英

How to inflate custom layout in runtime while avoiding redundant layout in the view hierarchy - Android

In general, I want to know how should I inflate custom layout defined in XML at runtime without having a redundant layout in my views hierarchy.

Now, in particular:

I have a custom layout which is declared in an xml, my_relative_layout.xml and its root element is a RelativeLayout. I have also defined a class which extends RelativeLayout called MyRelativeLayout.java .

How can I inflate my_relative_layout.xml in my MyRelativeLayout.java in a way that I won't have a redundant RelativeLayout in the hierarchy.

I tried using <merge> - it caused that all the root element attributes in my_relative_layout.xml didn't affect so my layout content was messed up.

I also tried to declare my custom layout class as the root element in my_relative_layout.xml , but got inflation exception (i tried both setting root element to null or this, while inflating the xml in MyRelativeLayout.java - with true or false in attach to root).

I ended up using the <merge> tag. Note that you must set all the RelativeLayout layout params at runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM