25

I want to dynamically add some views to a LinearLayout that is already defined in XML.

I'm able to add views to the screen but they are not being placed 'inside' the right LinearLayout.

How can I get a reference to this specific Layout from code, similar to getting a View by using findViewById()?

1
  • 1
    If you end up with your views not in the right LinearLayout, it means you have a bad reference to it. Try checking if you find your linear layout by id in the correct way (aka by it's unique ID defined in the XML file). And without code, not much can be said. Commented Aug 13, 2010 at 14:10

3 Answers 3

49

As Marcarse pointed out you can do

ViewGroup layout = (ViewGroup) findViewById(R.id.your_layout_id);
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tv.setText("Added tv");
layout.addView(tv);

The LinearLayout class extends ViewGroup which itself extends the View class. This makes acquiring a reference to a layout as easy as getting a reference to another View.

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

1 Comment

Works for me, thanks! Only a note, in my case I was using horizontal orientation, but every time that I added the new item, it didn't appear. Only when I changed the orientation to vertical the new item appeared.
22

This should work:

LinearLayout layout = (LinearLayout) findViewById(R.id.your_layout_id);
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tv.setText("Added tv");
layout.addView(tv);

1 Comment

every time i reload the activity, the newly added views does not appear. I want to know that how to make those views to a ViewGroup so that they are added permanently? Thanks
1

Better Version: To add another layout in activity/Fragment

LayoutInflater mInflater = LayoutInflater.from(getActivity());
View mProgressBarFooter = mInflater.inflate(R.layout.spinner, null, false);
textLoader = (TextView) mProgressBarFooter.findViewById(R.id.footer_label);

Happy Coding(-:

2 Comments

How does the answer relate to the question?
This is what i was looking for.

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.