2011-06-16 102 views
17

我试图将动态内容添加到使用XML创建的视图中。如何将元素动态添加到使用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和动态的,而不是填充它只是一个虚拟的文字,但首先我必须得到这个工作。

任何帮助,欢迎。

亲切的问候 欧莱

我找到了解决办法!

我愚蠢我在我的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> 

希望这会帮助别人。感谢所有帮助!

+0

我不明白你想做什么。如何创建自定义视图?我认为它更好 – Hein 2011-06-16 08:36:53

+0

通过定制视图你意味着动态创建整个视图?如果有人提出一个愚蠢的问题,我对他的原谅是很新的。我尝试过这种方式,但是我无法让设计和布局以这种方式工作,所以我从头开始。 – Olle 2011-06-16 08:55:52

回答

6

将视图添加到视图中的方式基本上是正确的 - 您只需通过ID获取容器对象,然后添加它们即可。

它看起来像你设置的内容视图是错误的看法,虽然。您应该夸大视图,添加子项并将其设置为内容视图,或者从资源ID设置内容视图,然后进行操作。你在做什么是操纵一个视图,然后添加一个不同的视图。尝试将你的setContentView(...)移动到块的开始位置。

+1

它没有为我工作。我在顶部''LayoutInflater inflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 查看v = inflater.inflate(R.layout.profile_list,null); //查找滚动查看 ScrollView sv =(ScrollView)v.findViewById(R.id.scrollView1);'我把//显示视图 setContentView(v);'last – Olle 2011-06-16 09:03:09

+1

非常感谢!如果我能,我会投票支持你的帖子。 – Olle 2011-06-16 10:33:52

相关问题