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.

Alexander Farber
  • 18,345
  • 68
  • 208
  • 375
celestialorb
  • 1,798
  • 5
  • 25
  • 48
  • I think that this is a duplicate of [Declaring a custom android UI element using XML](http://stackoverflow.com/questions/2695646/declaring-a-custom-android-ui-element-using-xml) – Casebash Aug 11 '10 at 00:03

1 Answers1

3

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
  • 22,993
  • 5
  • 50
  • 60