2013-08-23 91 views
0

我面临的一个问题是,我需要在滚动视图内部生成动态视图。点击按钮后应该生成视图。动态生成滚动条内部的布局视图

第一个按钮点击,它工作正常,但第二个后单击它与错误而失败“java.lang.IllegalStateException:滚动型只能承载一个直接子”

谁能帮助我得到这个固定。

我的主要活动布局,其中滚动型是activity_main.xml中:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" 
     tools:context=".MainActivity" android:layout_width="match_parent" android:layout_height="match_parent" 
     android:id="@+id/parentRL"> 
    <Spinner android:id="@+id/spinState" android:layout_width="wrap_content" android:layout_height="wrap_content"/> 
    <Spinner android:id="@+id/spinCity" android:layout_width="wrap_content" android:layout_height="wrap_content" 
     android:layout_below="@id/spinState"/> 
    <TextView android:id="@+id/cityCount" android:layout_width="wrap_content" android:layout_height="wrap_content" 
     android:layout_toRightOf="@id/spinCity" android:layout_below="@id/spinState" android:layout_marginLeft="5dp" 
     android:textIsSelectable="false"/> 
    <Button android:id="@+id/showAddress" android:layout_width="wrap_content" android:layout_height="wrap_content" 
     android:layout_toRightOf="@id/spinState" android:onClick="populateAddress" android:text="Search"/> 
    <ScrollView android:id="@+id/scView" android:layout_width="match_parent" android:layout_height="wrap_content" 
     android:layout_below="@id/spinCity"> 
    </ScrollView> 
</RelativeLayout> 

而且需要与滚动型附加视图布局是address_layout.xml:

<?xml version="1.0" encoding="utf-8"?> 
<TextView android:id="@+id/center" android:layout_width="wrap_content" xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_height="wrap_content" android:text="@string/hello_world" android:layout_margin="10dp" 
     android:textColor="#FF0000" android:textSize="30dp" 
/> 

在主要活动中,内按钮点击收听者:

LayoutInflater inflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View myView = inflater.inflate(R.layout.address_layout, null); 
TextView _c_ = (TextView)(myView.findViewById(R.id.center)); 
_c_.setVisibility(View.VISIBLE); 
_c_.setText(my_random_number); 
View insertPoint = findViewById(R.id.scView); 
((ViewGroup) insertPoint).addView(myView, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); 

回答

0

android scrollview仅支持孩子so它抛出java.lang.IllegalStateException异常。 您应该在滚动视图中添加一个LinearLayout或Relative布局,然后将子项添加到该布局中。

<ScrollView android:id="@+id/scView" android:layout_width="match_parent" android:layout_height="wrap_content" 
     android:layout_below="@id/spinCity"> 
<LinearLayout android:id="@+id/layout" 
android:layout_width="match_parent" android:layout_height="wrap_content"> 
    </LinearLayout> 
    </ScrollView>