title: Android - Writing a custom (compound) component
body: <p>The Android app I'm currently developing has a main activity that has grown quite large. This is mainly because it contains a <code>TabWidget</code> with 3 tabs. Each tab has quite a few components. The activity has to control of all those components at once. So I think you can imagine that this Activity has like 20 fields (a field for almost every component). Also it contains a lot of logic (click listeners, logic to fill lists, etc).</p>
  
  <p>What I normally do in component based frameworks is to split everything up into custom components. Each custom component would then have a clear responsibility. It would contain it's own set of components and all other logic related to that component.</p>
  
  <p>I tried to figure out how this can be done, and I found something in the Android documentation what they like to call a "Compound Control". (See <a href="http://developer.android.com/guide/topics/ui/custom-components.html#compound" rel="noreferrer">http://developer.android.com/guide/topics/ui/custom-components.html#compound</a> and scroll to the "Compound Controls" section) I would like to create such a component based on an XML file defining the view structure.</p>
  
  <p>In the documentation it says:</p>
  
  <blockquote>
    <p>Note that just like with an Activity,
    you can use either the declarative
    (XML-based) approach to creating the
    contained components, or you can nest
    them programmatically from your code.</p>
  </blockquote>
  
  <p>Well, that's good news! The XML-based approach is exactly what I want! But it doesn't say how to do it, except that it is "like with an Activity"... But what I do in an Activity is call <code>setContentView(...)</code> to inflate the views from XML. That method is not available if you for example subclass <code>LinearLayout</code>.</p>
  
  <p>So I tried to inflate the XML manually like this:</p>
  
  <pre><code>public class MyCompoundComponent extends LinearLayout {
  
      public MyCompoundComponent(Context context, AttributeSet attributeSet) {
          super(context, attributeSet);
          LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
          inflater.inflate(R.layout.my_layout, this);
      }
  }
  </code></pre>
  
  <p>This works, except for the fact that the XML I'm loading has <code>LinearLayout</code> declared as the root element. This results in the inflated <code>LinearLayout</code> being a child of <code>MyCompoundComponent</code> which itself already is a <code>LinearLayout</code>!! So now we have a redundant LinearLayout in between <code>MyCompoundComponent</code> and the views it actually needs.</p>
  
  <p>Can somebody please provide me with a better way to approach this, avoiding having a redundant <code>LinearLayout</code> instantiated?</p>