Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Add a view to a specific Layout from code

Tags:

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()?

like image 970
Erik Avatar asked Aug 13 '10 14:08

Erik


People also ask

Is this possible to add views in a layout dynamically in Android?

You may have to adjust the index where you want to insert the view. Additionally, set the LayoutParams according to how you would like it to fit in the parent view. e.g. with FILL_PARENT , or MATCH_PARENT , etc. it's where ever you want to put the dynamically generated layout in your main view.

How do you create a programmatically view?

If you create a View via a constructor (e.g., Button myButton = new Button(); ), you'll need to call setLayoutParams on the newly constructed view, passing in an instance of the parent view's LayoutParams inner class, before you add your newly constructed child to the parent view.

How do you create a view in linear layout?

To create a linear layout in which each child uses the same amount of space on the screen, set the android:layout_height of each view to "0dp" (for a vertical layout) or the android:layout_width of each view to "0dp" (for a horizontal layout). Then set the android:layout_weight of each view to "1" .


1 Answers

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.

like image 167
Janusz Avatar answered Oct 23 '22 11:10

Janusz