Подтвердить что ты не робот

Динамическое добавление содержимого в линейную компоновку?

Если, например, я определил корневую линейную компоновку, ориентация которой вертикальная:

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>

В корневой линейной компоновке я хотел бы добавить несколько дочерних линейных макетов, каждая из которых ориентирована по горизонтали. Со всем этим я мог бы получить таблицу как выход.

Например, root с дочерним расположением, например:

<?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>

Поскольку число дочерних линейных макетов и их содержимое довольно динамичны, я решил программно добавить контент в корневой линейный макет.

Как можно добавить второй макет к первому программному, который также может установить все атрибуты макета для каждого дочернего элемента и добавить еще другие элементы внутри дочернего элемента?

4b9b3361

Ответ 1

В onCreate() напишите следующее

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 и view3 являются вашими TextView s. Они легко создаются программно.

Ответ 2

LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
View child = getLayoutInflater().inflate(R.layout.child, null);
layout.addView(child);

Ответ 3

Вы можете добиться каскадирования LinearLayout следующим образом:

LinearLayout root = (LinearLayout) findViewById(R.id.my_root);    
LinearLayout llay1 = new LinearLayout(this);    
root.addView(llay1);
LinearLayout llay2 = new LinearLayout(this);    
llay1.addView(llay2);