首先,这是我的代码:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linLayout = new LinearLayout(this);
TextView text=new TextView(this);
ArrayList<String> recup = recupData();
List<TextView> lvariables = new ArrayList<TextView>();
int i = 0;
for(i=0;i<recup.size();i++){
text.setText(recup.get(i)+"\n");
lvariables.add(text);
linLayout.addView(lvariables.get(i));
}
setContentView(linLayout);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
现在,我的问题是: 如何在同一布局(例如一个在另一个下面)上显示 N 个 TextView (在循环中生成并存储在我的列表中)!?
根据您可以看到的代码,我收到“IllegalState”异常!
这是 XML 文件,以防万一:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
</RelativeLayout>
(不是很短吗!?:/)
我很清楚这个问题是基本且愚蠢的,但我无法让我的大脑理解 Android 哲学的工作方式!
如果有人有足够的耐心来帮助我解决我的问题,即使它已经在 StackOverFlow 上讨论了一百万次,我也会非常感激!
我非常感谢您提供的任何帮助! 哦,请原谅我的英语,我是法国人......:D
最佳答案
您总是添加相同的 TextView,但这是不允许的
更改:
for(i=0;i<recup.size();i++){
text.setText(recup.get(i)+"\n");
lvariables.add(text);
linLayout.addView(lvariables.get(i));
}
与
for(i=0;i<recup.size();i++){
TextView text=new TextView(this);
text.setText(recup.get(i)+"\n");
lvariables.add(text);
linLayout.addView(text);
}
编辑:将 LinearLayout 的方向更改为垂直:
LinearLayout linLayout = new LinearLayout(this);
linLayout.setOrientation(LinearLayout.VERTICAL);
关于java - 非法状态异常 : Unable to add several TextViews in a View,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17568515/