tags:

views:

44

answers:

2

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  A: 

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);
Macarse
A: 

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.

Janusz
By using ViewGroup, it works perfectly!
Erik