How to inject a custom view to a viewGroup declared in an xml at runtime?

352 views Asked by At

I' ve designed a xml layout-file with some standard ui-components in it. So far it works fine. In my Java-code I've implemented a custom view which extends a SurfaceView for the purpose of animating things. Now I want to inject this custom view at runtime to the ui defined in the layout-file. Do I have to provide for an empty view filler for that custom view in the XML? How does this work? Can you show me a simple code snippet please ? Thanks

3

There are 3 answers

0
resource8218 On BEST ANSWER

Use ViewGroup addView() method. Also you can use ViewStub

0
Darpan On

You may use

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width=”match_parent”
    android:layout_height=”match_parent”
    android:background="@color/app_bg"
    android:gravity="center_horizontal">

    <include layout="@layout/titlebar"/>

where, this linearLayout is in basic layout while this layout in include is another layout file. So you can even reuse this layout multiple times.

Check examples here

0
Young Andy On

this way it works, but is there any more elegant way to do this, e.g. with a ViewStub ?

    // the animation-view:
    final LighthouseView lighthouseView = new LighthouseView(this, controller);
    controller.registerView(lighthouseView);

    setContentView(R.layout.activity_lighthouse);
    ViewGroup container = (ViewGroup) findViewById(R.id.lighthouse_container);
    container.addView(lighthouseView, 0);
    setContentView(container);