Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding content to a linear layout dynamically?

If for example I have 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> 

Inside the root linear layout, I would like to add multiple child linear layouts, each of the child linear layout orientation is horizontal. With all these I could end up with a table like output.

For example root with child layout such as:

<?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 linear layouts and their contents are quite dynamic, I've decide to add content to the root linear layout programmatically.

How can the second layout be added to the first programmatically, which could also set all the layout attributes for each child and add more other elements inside child?

like image 469
Leem Avatar asked Jul 12 '11 08:07

Leem


People also ask

How do you add a space 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" .

Is linear layout better than constraint layout?

So at the rendering, it doesn't have to calculate a lot just render with one onMeasure() method call. That is why the linear layout is more efficient in terms of performance.


1 Answers

In your 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 TextViews. They're easily created programmatically.

like image 155
Sherif elKhatib Avatar answered Oct 02 '22 14:10

Sherif elKhatib