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);
}
}
Have res/layout/view_layout.xml
start with a <merge>
element instead of a LinearLayout
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With