2012-06-16 32 views
1

我想在運行時向一個滾動視圖添加一堆TextViews,但我得到The specified child already has a parent. You must call removeView on the child's parent first運行時滾動視圖中的多個TextViews

main.xml中

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

    <LinearLayout 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/layout" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" > 
    </LinearLayout> 

</ScrollView> 

testapp

@Override 
public void onCreate(Bundle savedInstanceState) { 

    TextView[] data; 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    View layout = findViewById(R.id.layout); 

      ....................................... 

    data = new TextView[10]; 

    for (int i = 0; i < 10; i++) { 

     data[i] = new TextView(this); 
     data[i].setText("data = " + i); 


     ((ViewGroup) layout).addView(data[i]); 
    } 

    setContentView(layout); 

} 
+0

你試圖重新創建ListView? – Selvin

+0

爲什麼你再次使用這個setContentView(佈局).. –

回答

1

在這樣的單個Activity中,您不能使用setContentView()兩次。那就是問題所在。
看看這個答案here

視圖只能有一個父。您正在添加的視圖(我猜是重用)已經是另一個視圖層次結構的一部分。如果你真的想重用它(我建議你可能不這樣做),那麼你必須在現有的視圖層次結構中將它從它的父代中分離出來。

1

我認爲這個問題是佈局變量。

當您使用此setContentView(佈局)時,它現在已經具有父XML滾動視圖按照XML現在;所以此嘗試在不同的父級中添加版式..

+0

對不起,但我想我們可以有setContentView()兩次http://www.androiddiscuss.com/1-android-discuss/38205.html –

+0

請確認我是否是我錯誤.......... –

相關問題