2011-06-16 37 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

相關問題