views:

713

answers:

1

I am building a Android app and I am a bit struggling with custom Views.

I would like to have a reusable View that consist of a few standard layout elements. Let's say a relativelayout with some buttons in it.

How should I proceed. Should I create a custom view class that extends RelativeLayout and programmaticly add those buttons? I would think that's a bit overkill?

What's the way to do it properly in Android?

+3  A: 

Here are some rough steps regarding one way to create a custom aggregate view:

  1. extend RelativeLayout
  2. Provide a constructor in your new class that accepts Context and AttributeSet, making sure to call the superclass first. Do no add anything at this point. Wait until the next step.
  3. override the onFinishInflate method, where you can add your contents through Java code or inflating an XML resource
  4. Add any event handlers, etc
  5. Optionally create a resources file if your widget will require attributes to be set.

Steve
Note that for the XML layout resource, the `<merge>` root element works nicely for this scenario.
CommonsWare
I need to mention, that using the `onFinishInflate` method fails to inflate `<merge>` rooted layouts. If you inflate in the `onCreate` method, it does work.
Peterdk