androidxmlandroid-layoutandroid-include

programmatically check if view includes specific layout?


I have a layout section.xml and some other layouts that may include section.xml.

Now suppose I have an inflated layout, for example layout.xml, and I want to know does it include section.xml or not?

I can loop through all children of layout.xml, but I do not know how I can detect if a child is section.xml that is included here or not. I know I can try to set a unique id for section.xml and check ids of children of layout.xml, but the problem is the uniqueness; because other developers may forget this rule.


Solution

  • Now suppose I have an inflated layout, for example layout.xml, and I want to know does it include section.xml or not?

    That is not possible, in any direct fashion. Once a layout resource is inflated, there are no signs of the layout resource itself. This is both for direct inflation (e.g., inflate() that you call) and indirect inflation (e.g., <include> in a layout to pull in another layout).

    I know I can try to set a unique id for section.xml

    I am interpreting this as meaning "set a unique ID for a widget inside of section.xml". That is the closest thing that you can do at runtime that resembles the rule that you are trying to implement.

    and check ids of children of layout.xml, but the problem is the uniqueness; because other developers may forget this rule.

    Then your ID was not unique enough. :-) Use diceware to come up with something that nobody else will use by accident, such as android:id="aquamarineBakeryUprightAnxietyPlugAlchemy". Ideally, use this on a widget that you do not need to reference from elsewhere in the layout or from your code.

    Alternatively, implement a Lint rule to check things at compile time. In Lint processing, layout resources are still layout resources. So, if certain layout resources must <include> your section layout, you can confirm that via a Lint rule. Or, if certain layout resources must not <include> your section layout, you can confirm that too. Unfortunately, writing Lint rules is not that well documented.