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()
?
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.
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.
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" .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With