1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Argh, turns out it was so simple!! By unsuccessfully, I meant that my content wasn't visible. However, this was because I was using fill_parent, which took up all of the visible area. Thanks hackbod.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.