How to Programmatically Add Views to Views
Let's say I have a
LinearLayout, and I want to add a View to it, in my program from the Java code. What method is used for this? I'm not asking how it's done in XML, which I do know, but rather, how can I do something along the lines of this sample code?
(One View).add(Another View)
Like one can do in Swing.
addView is the correct answer, but you need to do a little more than that to get it to work.
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.
For example, you might have the following code in your
onCreate() function assuming your LinearLayout has id
LinearLayout myLayout = findViewById(R.id.main); Button myButton = new Button(this); myButton.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)); myLayout.addView(myButton);
Making sure to set the LayoutParams is important. Every view needs at least a layout_width and a layout_height parameter. Also getting the right inner class is important. I struggled with getting Views added to a TableRow to display properly until I figured out that I wasn't passing an instance of TableRow.LayoutParams to the child view's setLayoutParams.