我尝试让 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) 这一行 我做错了什么? 谢谢
最佳答案
异常很明显:您不能向 ScrollView 添加多个子项。根据您的代码,我假设 linearLayout2
已经在 ScrollView 中了?如果是这样,那你就不需要了
this.scrollView.addView(this.linearLayout);
完全没有,因为您将 TextView 添加到已经在 ScrollView 中的 LinearLayout
关于android - 在 Android 上动态添加 TextView 到 ScrollView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7930602/