views:

28

answers:

1

I have a custom View that I'd like to specify the layout of in an XML file rather than through code, is there anyway I can take an Android XML layout file and use it to flush out my custom View's content? I know it can be done in an Activity via the setContentView method, but there doesn't seem to be a similiar method for Views.

Thanks in advance for any help!

Regards, celestialorb.

+1  A: 

Here's the basic overview: In code for your activity, use findViewById to get the container of the subview you want to define in XML in the activity's main view. Then, use mySubview = getLayoutInflater().inflate(R.layout.mysubview, mycontainerInRootView) to build the new contained view. Finally, you can use the returned subviews findViewById to hook the subview's controls into the main activity.

In a custom View class, you similarly need to just get a LayoutInflater instance do do the work for you, but the details will probably work out a little differently. I'd make the custom View a ViewGroup subclass to start, then use LayoutInflater.from(ctx) in the constructor to get the inflater and go from there. It would look something like mContents = LayoutInflater.from(ctx).inflate(R.layout.mycustomview, this).

Walter Mundt