我一直在努力找到一个合适的答案,如何在android studio的运行时将组件添加到片段中的布局。
特别:
我有A类下载和解析XML文件。片段B实例化此A类,并应显示下载的项目。 (现在只是一个textview)
这是应该显示textView的XML文件。这些项目应显示在两列中。我知道如何在XML文件中创建布局,但我不知道如何以编程方式执行它。我也读过一些关于inflaters的东西,但我不知道它是否符合这个目的。
<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>
所以这里是片段B中的代码,它目前只是更改了两个现有文本视图的文本,它们运行得很好。
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());
}
}
目标是通过while循环为每次迭代添加一个新的TextView到父布局。此TextView应显示it.next()的内容。
在此先感谢您,如果您需要任何进一步的信息,请告诉我。
如果你想将TextView
添加到TableRow
。
首先,为TableRow
添加一个id
<TableRow
android:id="@+id/table1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:paddingTop="10dp">
然后,在你的onCreate
tableRow = findViewById(R.id.table1); // tableRow is a global variable
在片段中添加一个空格
private void addTextView(String atext) {
TextView txt = new TextView(getActivity());
txt.setText(atext);
tableRow.addView(txt);
// here you can add other properties to the new TextView (txt)
}
然后
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()) {
String atxt = it.next();
System.out.println("Data is " + atxt);
addTextView(atxt);
}
}