繁体   English   中英

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

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

我有以下内容:-带有字符串的映射,如:[“ Color:blue”,“ Size:big”],称为detailsArray

具有LinearLayout和现有TextView的现有ScrollView:

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

我故意省略了诸如宽度,高度,xml模式之类的通用字段。

现在,我想以编程方式添加textViews。 我不知道他们有很多:

    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);

但是我遇到一个例外:

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

我该怎么办? 先感谢您。

您应该删除sv.addView(llay); 因为您基本上是将线性布局两次添加到同一个ScrollView中 ,所以您将收到异常,以及为什么在开始时删除AllViews可以解决此问题。 在完成for循环调用之后

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

应该使它刷新其内容。

暂无
暂无

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

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