Adrime Adrime - 5 months ago 36
Java Question

Create a composite view in Android

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

MyComplexView
), for example a
RelativeLayout
with an
Imageview
, a
TextView
, and a
Button
.

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

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:

this.findViewById(R.id.myView);
Comments