shoota
shoota

Reputation: 111

How to programmatically add a layout to end of the current layout?

It seems like this should be easy but no luck so far. I set my Activity's main layout and then depending on which button is clicked I need to add a specific layout to end of the current main layout.

Main Activity:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //live_video_layout is a vertical LinearLayout
    setContentView(R.layout.live_video_layout);

    //Psuedo code for clarity; these layouts are ScrollViews that will sit under live_video_layout seen above
    if(button1 is clicked)
      {add R.id.first_layout under live_video_layout}

    else if(button2 is clicked)
      {add R.id.second_layout under live_video_layout
}

Any guidance here would be greatly appreciated, I'm all out of ideas.

Upvotes: 3

Views: 2317

Answers (2)

Rami
Rami

Reputation: 7929

You can prepare two Layouts in your xml file, the first one for your video views and the second for the dynamic layouts:

main_activity.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/live_video_container">

        <!-- include your live_video_layout.xml or directly add  your views-->

    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/dynamic_layouts_container">
        <!-- here we'll add layouts from java code depending on buttons click -->
    </LinearLayout>
</LinearLayout>

Then in your activity:

    private LinearLayout mDynamicLayoutsContainer;
    private LayoutInflater mInflater;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main_activity);

        mInflater = LayoutInflater.from(context);
        mDynamicLayoutsContainer = (LinearLayout) findViewById(R.id.dynamic_layouts_container);

        if(button1 is clicked){

          View  firstLayout = mInflater.inflate(R.layout.first_layout , null, false);
          mDynamicLayoutsContainer.addView(firstLayout);

        }else if(button2 is clicked){

          View  secondLayout = mInflater.inflate(R.layout.second_layout , null, false);
          mDynamicLayoutsContainer.addView(secondLayout);

        }
   }

Upvotes: 3

Patricia
Patricia

Reputation: 2865

You need a third layout as parent. You put then R.layout.live_video_layout and the new one in this third layout.

Upvotes: 0

Related Questions