Tuesday, February 17, 2009

Android Custom Component Merge

I created my custom component that extends LinearLayout. In that post I show that the root element of the components XML is a <LinearLayout ...> element. That ended up getting in the way. When the LayoutInflater built the view in my Java PersonComposite extends LinearLayout the default behavior was that my java class now had one child, the LinearLayout that is the root of the XML. This meant that each use of <my.app.PersonComposite ...> in other view XML would never apply configuration to the Linearlayout that has any effect.

Wow. Even I don't understand that. Let's try this way. The LayoutInflater, actually created the following structure (details omitted for brevity):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout >
<LinearLayout >
<TextView .../>
<TextView .../>
</LinearLayout>
</LinearLayout>
So any attempts to use the component like this would never change the orientation of the two nested TextView Components because the configuration was applied to the outer LinearLayout:
<my.app.PersonComposite
android:id="@+id/person"
android:orientation="vertical"
/>
Solve this problem by using <merge> as the root element. And make sure you invoke LayoutInflater:

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View inflatedView = inflater.inflate(R.layout.person_composite, this);
Now the person_composite.xml looks something like this:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >
<TextView .../>
<TextView .../>
</merge>
You can see how this works by getting the android source from git and looking at the source code for the LayoutInflater.inflate method. then search that same source tree for an xml that uses <merge> as the root element. You'll find more than one.

2 comments:

Geetha Devi said...

Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ..
Android Training in velachery | Android Training in chennai

Saranya N said...

This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.Android Training in chennai with placement | Android Training in velachery