Reputation: 6202
I'd like to know if its considered bad practice to inflate child view from within a custom view's constructor, and if so maybe a reason as to why this is so ?
public class MyLinearLayout : LinearLayout
{
public MyLinearLayout (Context context, IAttributeSet attributes) : base(context, attributes)
{
LayoutInflater inflater = (LayoutInflater)context.ApplicationContext.GetSystemService(Context.LayoutInflaterService);
View child = inflater.Inflate(Resource.Layout.ChildView, null);
this.AddView(child);
}
}
versus
public class MyLinearLayout : LinearLayout
{
public MyLinearLayout (Context context, IAttributeSet attributes) : base(context, attributes)
{
View child = new ChildView(context);
child.LayoutParameters = new LayoutParameters(...);
this.AddView(child);
}
}
Thank you.
Upvotes: 0
Views: 78
Reputation: 25584
There is no issue with this approach, as it can be found in classes like NumberPicker
. If you use the LayoutInflater.inflate(int, ViewGroup, boolean)
method to attach to the root view, you can use Merge
optimizations. E.g.
View child = inflater.Inflate(R.layout.ChildView, this, true);
Upvotes: 1