如何在使用XML创建的视图中动态添加元素

29

我想要向一个使用XML创建的视图中添加动态内容。

我有一个名为“profile_list”的视图,其中包含一个ScrollView,我想要向其中添加一些元素。

以下是我尝试做的事情的一些代码。

// Find the ScrollView 
ScrollView sv = (ScrollView) this.findViewById(R.id.scrollView1);

// Create a LinearLayout element
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

// Add text
tv = new TextView(this);
tv.setText("my text");
ll.addView(tv);

// Add the LinearLayout element to the ScrollView
sv.addView(ll);

// Display the view
setContentView(R.layout.profile_list);

计划是添加一个TableLayout并动态填充它,不仅是虚拟文本,而是首先我必须让它工作。

欢迎任何帮助。

此致敬礼 Olle

我找到了解决方案!

太蠢了,我在XML文件中的ScrollView中留下了一个元素!

无论如何,这里有一个可行的示例:

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflater.inflate(R.layout.profile_list, null);

    // Find the ScrollView 
    ScrollView sv = (ScrollView) v.findViewById(R.id.scrollView1);

    // Create a LinearLayout element
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);

    // Add text
    TextView tv = new TextView(this);
    tv.setText("my text");
    ll.addView(tv);

    // Add the LinearLayout element to the ScrollView
    sv.addView(ll);

    // Display the view
    setContentView(v);

并且匹配的XML文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ScrollView 
        android:id="@+id/scrollView1" 
        android:clickable="true" 
        android:layout_weight="1" 
        android:layout_width="fill_parent" 
        android:layout_marginBottom="50px" 
        android:layout_height="fill_parent">
    </ScrollView>

</LinearLayout>

希望这能帮助到有需要的人。感谢所有的帮助!


我不太明白你想做什么。创建自定义视图怎么样?我认为这样会更好。 - Hein
你指的自定义视图是指动态创建整个视图吗?我在这方面还很新,所以如果问了一个愚蠢的问题请原谅。我尝试过这样做,但我无法让设计和布局以这种方式工作,所以我重新开始了。 - Olle
1个回答

6
你添加视图的方法基本上是正确的-你只需要通过ID获取容器对象,然后添加它们。
但是看起来你设置的内容视图是错误的。你应该先填充视图,添加子视图,然后将其设置为内容视图,或者从资源ID设置内容视图,然后进行操作。你正在操作一个视图,然后添加另一个视图。尝试将setContentView(...)移动到块的开头。

1
对我来说没用。我在顶部尝试了这个:LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflater.inflate(R.layout.profile_list, null); // 找到ScrollView ScrollView sv = (ScrollView) v.findViewById(R.id.scrollView1);然后我把// 显示视图放在最后的setContentView(v);里。 - Olle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接