在android studio中运行时在片段中添加组件

在android studio中运行时在片段中添加组件,android,android-layout,android-fragments,layout-inflater,Android,Android Layout,Android Fragments,Layout Inflater,我一直在努力寻找一个合适的答案,如何在androidstudio的运行时在片段中向布局添加组件 具体而言: 我有一个类,可以下载和解析XML文件。片段B实例化了这个类A,应该显示那些下载的项目。(目前只提供文本视图) 这是显示textView的XML文件。项目应显示在两列中。我知道如何在XML文件中创建布局,但不知道如何通过编程来实现。我也读过一些关于充气机的书,但我不知道它是否适合这个用途 如果要将文本视图添加到表格行 首先,将id添加到TableRow <TableRow

我一直在努力寻找一个合适的答案,如何在androidstudio的运行时在片段中向布局添加组件

具体而言:

我有一个类,可以下载和解析XML文件。片段B实例化了这个类A,应该显示那些下载的项目。(目前只提供文本视图)

这是显示textView的XML文件。项目应显示在两列中。我知道如何在XML文件中创建布局,但不知道如何通过编程来实现。我也读过一些关于充气机的书,但我不知道它是否适合这个用途


如果要将
文本视图
添加到
表格行

首先,将id添加到
TableRow

    <TableRow
        android:id="@+id/table1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:paddingTop="10dp">
在片段中添加一个空格

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);
    }
}
public void onStart(){
super.onStart();
ArrayList categories=新的ArrayList();
XMLHandler getXML=新的XMLHandler();
getXML.execute();
categories=getXML.getCategories();
迭代器it=categories.Iterator();
while(it.hasNext()){
字符串atxt=it.next();
System.out.println(“数据为”+atxt);
addTextView(atxt);
}
}

谢谢,这一个对我很有用。如果其他人遇到此问题:当从片段访问tableRow时,必须调用
View=inflater.inflate(R.layout.Fragment\u layout,container,false)然后
view.findViewById(R.id.table1)在片段的onCreateView方法中,否则将获得nullpointer异常。
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);
    }
}