简体   繁体   English

如何使用LinearLayout和现有TextView以编程方式将TextView添加到ScrollView

[英]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 我有以下内容:-带有字符串的映射,如:[“ Color:blue”,“ Size:big”],称为detailsArray

An existing ScrollView with a LinearLayout and existing TextViews: 具有LinearLayout和现有TextView的现有ScrollView:

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

I've ommited common fields like width, height, xml schemas on purpose. 我故意省略了诸如宽度,高度,xml模式之类的通用字段。

Now I want to add textViews programmatically. 现在,我想以编程方式添加textViews。 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); 您应该删除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. 因为您基本上是将线性布局两次添加到同一个ScrollView中 ,所以您将收到异常,以及为什么在开始时删除AllViews可以解决此问题。 After you finish the for loop call 在完成for循环调用之后

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

should make it refresh it's content. 应该使它刷新其内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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