ab11
ab11

Reputation: 20100

Android: how to define layout for custom View in xml?

I would like to create a class MyView, which extends LinearLayout. MyView has a fairly complex View hierarchy, with a number of children which have children, etc. I would like to define this hierarchy in Xml. However, I would also like MyView to be reusable in code. I would like MyView to be instantiated with its complex hierarchy without creating or modifying any additional Xml files; I would like some other LinearLayout to be able to do something like:

MyView view = new MyView(linearLayout.getContext());
linearLayout.addView(view);

This could be accomplished by setting up the View hierarchy in java code in the constructor of MyView. But it seems like I should be able to use a xml layout to do this in the constructor. I guess basically I am looking for the equivalent of Activity.setContentView(...) for a View; but can't find it.

Upvotes: 1

Views: 808

Answers (1)

Chris
Chris

Reputation: 23179

Since your MyView class extends LinearLayout, you can just do this in the constructor:

LayoutInflater inflater = LayoutInflater.from(context);
inflater.inflate(R.layout.myviewlayout, this);

Upvotes: 3

Related Questions