Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Programmatically Add Views to Views

Tags:

android

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.

like image 204
Moki Avatar asked Mar 07 '10 09:03

Moki


People also ask

How do I add a view in another view?

All you need to do is inflate the view programmatically and it as a child to the FrameLayout by using addChild() method. Then during runtime your view would be inflated and placed in right position. Per Android recommendation, you should add only one childView to FrameLayout [link].

How to add View Dynamically?

This example demonstrates How to Dynamically Add Views into View. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.


1 Answers

Calling 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 R.id.main:

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.

like image 138
Brian Cooley Avatar answered Sep 20 '22 01:09

Brian Cooley