java - 非法状态异常 : Unable to add several TextViews in a View

标签 java android layout textview illegalstateexception

首先,这是我的代码:

    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/

相关文章:

java - Android:使线程每秒运行的标准方法

java - Android:从单独的类文件调用 AsyncTask 内部类

html - 尽管删除了旧的样式表,替换后的导航栏仍具有与旧的样式表冲突的样式表

java - 在数组中搜索值并获取数组名称

java - 访问 Lotus Domino 服务器时不同的 View 内容

java - 查找任意两个列表值之和是否等于给定值

java - char常量显示在Javadoc "Constant Field Values"页面

java - android 计划的作业是否在应用程序升级后仍然存在?

java - 使用哪种布局?

html - 纯 css 弹出子菜单无法正确显示