Add content dynamically to linear layout?

If, for example, I defined a root linear layout whose orientation is vertical:

main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/my_root" android:layout_height="wrap_content" android:layout_width="fill_parent" android:orientation="vertical" <!-- I would like to add content here dynamically.--> </LinearLayout> 

In the root linear layout, I would like to add several child linear layouts, each of which is oriented horizontally. With all this, I could get the table as an output.

For example, root with a child location, for example:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/my_root" android:layout_height="wrap_content" android:layout_width="fill_parent" android:orientation="vertical" <!-- 1st child (1st row)--> <LinearLayout ... android:orientation="horizontal"> <TextView .../> <TextView .../> <TextView .../> </LinearLayout> <!-- 2nd child (2nd row)--> ... </LinearLayout> 

Since the number of child line layouts and their contents are quite dynamic, I decided to programmatically add content to the root linear layout.

How can I add a second layout to the first program, which can also set all the layout attributes for each child element and add other elements inside the child element?

+53
android android-layout
Jul 12 '11 at 8:15
source share
3 answers

In onCreate() write the following

 LinearLayout myRoot = (LinearLayout) findViewById(R.id.my_root); LinearLayout a = new LinearLayout(this); a.setOrientation(LinearLayout.HORIZONTAL); a.addView(view1); a.addView(view2); a.addView(view3); myRoot.addView(a); 

view1 , view2 and view3 are your TextView s. They are easy to create programmatically.

+74
Jul 12 '11 at 8:26
source share
— -
 LinearLayout layout = (LinearLayout)findViewById(R.id.layout); View child = getLayoutInflater().inflate(R.layout.child, null); layout.addView(child); 
+58
Jul 12 '11 at 8:25
source share

You can cascade LinearLayout as follows:

 LinearLayout root = (LinearLayout) findViewById(R.id.my_root); LinearLayout llay1 = new LinearLayout(this); root.addView(llay1); LinearLayout llay2 = new LinearLayout(this); llay1.addView(llay2); 
+5
Jul 12 '11 at 8:27
source share



All Articles