简体   繁体   中英

How to add TextView's programatically to a ScrollView with a LinearLayout and existing TextViews

I have the following: -A map with Strings like:["Color: blue","Size: big"] called detailsArray

An existing ScrollView with a LinearLayout and existing TextViews:

<ScrollView>
    <LinearLayout>
        <TextView
            android:text="something: else"
        />
    </LinearLayout>
</ScrollView>

I've ommited common fields like width, height, xml schemas on purpose.

Now I want to add textViews programmatically. I don't know hoy many are they:

    TextView detail;
    LinearLayout llay = (LinearLayout)fragmentView.findViewById(R.id.container);    
    for (int i = 0; i < detailsArray.length; i++) {
                    detail = new TextView(fragmentView.getContext());
                    detail.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
                    detail.setText(detailsArray[i]);
                    llay.addView(detail);
                }
        ScrollView sv = (ScrollView) fragmentView.findViewById(R.id.scroll_view);
        sv.addView(llay);

But I'm getting an exception:

04-17 12:38:09.975: E/AndroidRuntime(3361): Caused by: java.lang.IllegalStateException: ScrollView can host only one direct child

What should I do? Thank you in advance.

You should remove sv.addView(llay); as you are basically adding the linear layout twice to the same ScrollView - that the exception you are getting and why when you removeAllViews in the beginning it solves the issue. After you finish the for loop call

sv.invalidate(); 
sv.requestLayout(); 

should make it refresh it's content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM