How do I design a custom Android control and use it in Xml?
-
26-09-2019 - |
Question
I understand how to create a custom Android control, and I believe I understand how to pull attributes for it from the Xml layout. I don't know, however, how to get any children elements from it.
Here's a visual example of what I'm trying to accomplish:
public class Menu extends LinearLayout
{
// Custom Code
}
public class MenuItem extends Button
{
// Custom Code
}
<!-- Layout -->
<?xml version="1.0" encoding="utf-8"?>
<Menu>
<MenuItem/>
<MenuItem/>
</Menu>
When my Menu is created, how do I get references to the two MenuItems?
Solution
You should use an android:id
to do that. If you will not know how many childs you will have:
LinearLayout
extends ViewGroup, so you can use getChildAt()
and getChildCount()
to get those views.
OTHER TIPS
for accesing any control (custom or system ) an id is a must. by specifying an id you give it a unique identity. Using this id you can get a reference to that control.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow