Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating custom views without an extra view hierarchy

Tags:

android

I usually create a custom view, for say,

public class MyView extends LinearLayout{

  public MyView(Context context){
     super(context);

     //Inflating my custom layout
     LayoutInflater inflater = getLayoutInflater();
     inflater.inflate(R.layout.view_layout, this); 

  }

}

The problem with the above layout is, it will create a new LinearLayout and inflate R.layout.view_layout inside it, adding a new view hierarchy which is not preferred.

R.layout.view_layout contains RelativeLayout with many child elements, which I cannot add programatically by extending RelativeLayout (since positioning is difficult).

Having unnecessary hierarchies slow down my app.

What is the best way to create custom views/view group without an extra hierarchy level.

Solved as per the soln by CommonsWare:

XML Layout:

<merge>

<TextView ...
.../>

More items

</merge>

Since the XML layout had RelativeLayout as the parent view, I will extend RelativeLayout in the code instead of LinearLayout

public class MyView extends RelativeLayout{

      public MyView(Context context){
         super(context);

         //Inflating my custom layout
         LayoutInflater inflater = getLayoutInflater();
         inflater.inflate(R.layout.view_layout, this); 

      }

    }
like image 866
dcanh121 Avatar asked Oct 03 '22 17:10

dcanh121


1 Answers

Have res/layout/view_layout.xml start with a <merge> element instead of a LinearLayout.

like image 142
CommonsWare Avatar answered Oct 09 '22 15:10

CommonsWare