2011-11-06 97 views
0
 scrollview = (ScrollView)findViewById(R.id.detailedScrollView); 


    for (Quotation quotation : object.quotes){ 

      TextView quote = new TextView(this); 
      quote.setText(quotation.getQuote()); 
      quote.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 
      scrollview.addView(quote); 


     } 

假設有三個引號,那麼我想要三個textView。但是,上面的代碼崩潰了我的應用程序。任何明顯的錯誤?這裏是我得到的錯誤:在for循環中添加textViews

11-06 17:35:53.214: E/AndroidRuntime(1430): java.lang.IllegalStateException: ScrollView can host only one direct child 
+0

什麼的logcat的說?你得到的錯誤是什麼? –

+0

11-06 17:35:53.214:E/AndroidRuntime(1430):java.lang.IllegalStateException:ScrollView只能託管一個直接孩子 啊scrollview只能有一個孩子?我想我需要將所有內容放入linearLayout中,然後放入scrollview中? – Adam

回答

6

您不能直接在滾動視圖內添加視圖。 scrollview只能包含一個佈局對象。你需要做的是在你的滾動視圖中添加一個線性佈局,然後將textview添加到線性佈局

3

佈局容器的視圖層次結構可以由用戶滾動,允許它比物理顯示更大。 ScrollView是一個FrameLayout,這意味着你應該在其中放置一個包含整個內容滾動的子項;這個孩子本身可能是一個具有複雜對象層次結構的佈局管理器。一個經常使用的孩子是一個垂直方向的LinearLayout,呈現一個頂級項目的垂直數組,用戶可以滾動瀏覽。

TextView類還負責自己的滾動操作,因此不需要ScrollView,但使用這兩者可以在較大的容器內實現文本視圖的效果。 Please more detail

與問候, 心理

0

您需要添加一個 「的LinearLayout」 內滾動型(或 「RelativeLayout的」)。 假設你有佈局XML如下:

<ScrollView 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
    <LinearLayout 
    android:id="@+id/linearlayout1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"   
    >  
    </LinearLayout> 
</ScrollView> 

現在你要添加的「TextView的」編程,這是如下:

LinearLayout linearLayout =(LinearLayout) this.findViewById(R.id.linearlayout1); 
for (Quotation quotation : object.quotes){ 
    TextView quote = new TextView(this); 
    quote.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
    quote.setPadding(4, 0, 4, 0); //left,top,right,bottom 
    quote.setText(quotation.getQuote());   
    linearLayout.addView(quote); 
}