I've been struggling with finding an appropiate answer on how to add components to a layout in a fragment at runtime in android studio.
Specifically:
I have Class A which downloads and parses an XML file. Fragment B instantiates this Class A and should display those downloaded items. (just a textview for now)
This is the XML file in which the textView should be displayed. The items should be displayed in two columns. I know how to create the layout in the XML File but I have no idea on how to do it programatically. I've also read something about inflaters but I dont know if it fits this purpose.
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow
android:layout_width="match_parent"
android:layout_height="0dp"
android:paddingTop="10dp">
<TextView
android:id="@+id/columnItem"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="5dp"
android:layout_marginStart="5dp"
android:layout_weight=".5"
android:background="#c5c5c5"
android:gravity="center"
android:text="@string/CategoryLeft" />
</TableRow>
</ScrollView>
</TableLayout>
So here is the Code in Fragment B which currently just changes the text of the two existing textviews, that works just fine.
public void onStart() {
super.onStart();
ArrayList<String> categories = new ArrayList<>();
XMLHandler getXML = new XMLHandler();
getXML.execute();
categories = getXML.getCategories();
Iterator<String> it = categories.iterator();
while (it.hasNext()) {
System.out.println("Data is " + it.next());
columnItem.setText(it.next());
}
}
The goal is to add a new TextView for each iteration through the while loop to the parent layout. This TextView should display the content of it.next().
Thanks in advance and let me know if u need any further information.