2012-04-25 28 views
1

我要添加圖像滾動型,有代碼我試圖用:滾動型只能承載一個直接子例外

 ScrollView sv = (ScrollView)findViewById(R.id.scrollView2); 
     ImageView iv = new ImageView(this); 
     iv.setImageDrawable(new BitmapDrawable("PATH")); 
     iv.setScaleType(ScaleType.CENTER_INSIDE); 
     sv.addView(sv); 

我得到這個異常: java.lang.IllegalStateException:滾動型只能承載一個直接的孩子

那麼我應該如何將圖像添加到我的滾動視圖?

添加的代碼: XML:

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

    <ScrollView 
     android:id="@+id/scrollView1" 
     android:layout_width="100dp" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentTop="true" 
     android:background="#FF0000" > 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" > 

     </LinearLayout> 
    </ScrollView> 

    <ScrollView 
     android:id="@+id/scrollView2" 
     android:layout_width="200dp" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentTop="true" 
     android:layout_toRightOf="@+id/scrollView1" 
     android:background="#FFFF00" > 

     <LinearLayout 
      android:id="@+id/filesScrollerLayout" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" > 
     </LinearLayout> 
    </ScrollView> 

    <ImageView 
     android:id="@+id/imageView1" 
     android:layout_width="wrap_content" 
     android:layout_height="250dp" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentRight="true" 
     android:background="#FFFFFF" 
     android:layout_toRightOf="@+id/scrollView2" /> 

</RelativeLayout> 

和最終活動的onCreate調用此方法:

公共無效addImage(字符串路徑){

  LinearLayout sv = (LinearLayout)findViewById(R.id.filesScrollerLayout); 
     ImageView iv = new ImageView(this); 
     iv.setImageDrawable(new BitmapDrawable(path)); 
     iv.setScaleType(ScaleType.CENTER_INSIDE); 
     sv.addView(sv); 

} 

感謝。

+0

' sv.addView(sv)'看起來不對我。這種說法有什麼理由嗎? – Rajesh 2012-04-25 13:05:20

+0

我只是想添加圖像scrollView是否有其他解決方案旁邊呢? – Streetboy 2012-04-25 13:24:15

+0

將其更改爲'sv.addView(iv)'。 – Rajesh 2012-04-25 13:27:48

回答

8

這可能幫助..它告訴如此,因爲滾動型不能持有超過1名兒童..它需要用它來涵蓋其他視圖一個孩子..

<ScrollView> 
<LinearLayout 
android:id="@+id/child"> 
    <ImageView/> 
    ... 
    ... 
</LinearLayout> 
</ScrollView> 

你的情況

LinearLayout child = (LinearLayout)findViewById(R.id.child); 
     ImageView iv = new ImageView(this); 
     iv.setImageDrawable(new BitmapDrawable("PATH")); 
     iv.setScaleType(ScaleType.CENTER_INSIDE); 
     child.addView(sv); 
+0

現在我得到這個: java.lang.IllegalStateException:指定的子項已經有一個父項。您必須先調用子對象的父對象的removeView()。 – Streetboy 2012-04-25 13:15:19

+0

@Streetboy ..然後發佈您的所有代碼和xml .. – ngesh 2012-04-25 13:17:36

相關問題