jeffers102
jeffers102

Reputation: 61

Is it possible to add views dynamically to an XML based layout?

Lets say that I have a simple XML layout such as the following:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/my_container"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <LinearLayout android:id="@+id/leftContainer"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
           android:text="Col A - Text 1"
        /> 
    </LinearLayout>
    <LinearLayout android:id="@+id/rightContainer"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
           android:text="Col B - Text 1"
        /> 
    </LinearLayout>
</LinearLayout>

Then I want to add a TextView to the rightContainer LinearLayout. I am currently doing this, unsuccessfully:

LinearLayout container = (LinearLayout) findViewById(R.id.rightContainer);
TextView textToAdd = new TextView(this);
textToAdd.setText("Col B - Text 2");
container.addView(textToAdd);

I have looked at LayoutInflater, but am not sure how I would use it here. Any help would be appreciated, thanks! If I try calling setContentView(container), I receive a Force Close error.

Upvotes: 1

Views: 530

Answers (1)

hackbod
hackbod

Reputation: 91331

Don't call setContentView(), if you are using findViewById() then that view is already inside of your currently set content.

Adding views works fine. All a layout XML is, is a description of the views to create and add to the hierarchy. Make sure you are passing the correct layout params when adding a view -- here since container is a LinearLayout, you want a LinearLayout.LayoutParams.

You don't say in what way your code is "unsuccessful" so it is hard to help further.

Also you can use hierarchyviewer to look at what is actually going on in your view hierarchy.

Upvotes: 1

Related Questions