【问题标题】:Adding dynamically TextView to ScrollView on Android将 TextView 动态添加到 Android 上的 ScrollView
【发布时间】:2011-10-28 14:30:39
【问题描述】:

我尝试让 ScrollView 像 ListView 一样工作。 每一行都将是一个动态添加的 TextView。 所以我试试这段代码

this.scrollView = (ScrollView) findViewById(R.id.scrollView1);
this.linearLayout = (LinearLayout) findViewById(R.id.linearLayout2);
this.linearLayout.setOrientation(LinearLayout.VERTICAL);
TextView[] tx = new TextView[10];
for (int i = 0; i < 10; i++) {
    tx[i] = new TextView(this);
    tx[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tx[i].setText("This is the textviewNo" + i);
this.linearLayout.addView(tx[i]);
}
this.scrollView.addView(this.linearLayout);
setContentView(this.scrollView);

但我得到了这个例外

10-28 13:35:59.120: ERROR/AndroidRuntime(2346): Caused by: java.lang.IllegalStateException: ScrollView can host only one direct child

在 this.scrollView.addView(this.linearLayout) 这一行 我做错了什么? 谢谢

【问题讨论】:

    标签: android dynamic textview scrollview


    【解决方案1】:

    异常很清楚:您不能向 ScrollView 添加多个子项。根据您的代码,我假设linearLayout2 已经在 ScrollView 中?如果是这样,那你就不需要了

    this.scrollView.addView(this.linearLayout);
    

    完全没有,因为您将 TextViews 添加到已经在 ScrollView 内的 LinearLayout

    【讨论】:

      猜你喜欢
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多