Adrime Adrime - 1 year ago 154
Java Question

Create a composite view in Android

I'd like to create a custom view (I'll call it

), for example a
with an
, a
, and a

I'd like to declare an xml with the layout and then create the class:

MyComplexView extends RelativeLayout{...}

But I don't know what I should override to indicate which layout should be inflated.

How can I do this? Thanks

Answer Source

Something like this:

  1. add the constructors from the super class. (the one with just context is for creating the views programaticaly, the others are for when you add the view in XML.

  2. create a method called init() for example and call it from each constructor.

  3. inside the init method do:

    LayoutInflater.from(context).inflate(R.layout.my_view_layout, this, true);

now in inflate the additional params actually mean:

true -> attach the layout to the root in your case relative layout (pro-tip: so inside the xml you can have just merge tags if your layout root is also relative layout and align them in code so the hierarchy is simpler) or any layout you like.

this -> the layout to attach the inflated view to in your case the relative layout you are extending.

it will automatically be attached to the root -> extends RelativeLayout.

then you can use findViewById like:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download