【发布时间】:2019-04-15 07:30:59
【问题描述】:
我一直在努力寻找关于如何在运行时在 android studio 中将组件添加到片段中的布局的适当答案。
具体来说:
我有 A 类,它下载并解析 XML 文件。 Fragment B 实例化这个 Class A 并且应该显示那些下载的项目。 (现在只是一个文本视图)
这是应该在其中显示 textView 的 XML 文件。这些项目应显示在两列中。我知道如何在 XML 文件中创建布局,但我不知道如何以编程方式进行。我也读过一些关于充气机的文章,但我不知道它是否适合这个目的。
<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() 的内容。
提前致谢,如果您需要任何进一步的信息,请告诉我。
【问题讨论】:
标签: android android-layout android-fragments layout-inflater