【问题标题】:Android : when i put 'addView(..) inside a forloop i got error..Here we goAndroid:当我将'add View(..) 放在 for 循环中时,我得到了错误..我们开始
【发布时间】:2014-06-06 21:47:02
【问题描述】:

这里是代码示例:

     TableLayout ll = (TableLayout)findViewById(R.id.dyn_lyr);

LinearLayout 也一样

    //LinearLayout ll = (LinearLayout)findViewById(R.id.dyn_lyr);

    TextView tv1 = (TextView) findViewById(R.id.testEditText);
    tv1.setText("SomeTextGoesHere");

    for(int i=1 ; i<= 5 ; i++){
        ll.addView(tv1);
            }

LinearLayout/Table 在 ScrollView 内!

【问题讨论】:

  • 你不能多次添加同一个视图实例

标签: android android-linearlayout tablelayout


【解决方案1】:

没有足够的信息,但我猜 Tv1 已经有一个 parent 。我猜你应该每次都添加新的 TextView 。试试这个。好的,然后创建全新的 TextView

  for(int i=1 ; i<= 5 ; i++){
       TextView tv1 = new TextView(this);
       tv1.setText("SomeTextGoesHere");
       ll.addView(tv1);
   }

【讨论】:

    【解决方案2】:

    您应该动态创建 TextView 并添加到 ll...

    for(int i=1 ; i<= 5 ; i++){
        TextView tv1 = new TextView(getApplicationContext());
        tv1.setText("SomeTextGoesHere");
        ll.addView(tv1);
    }
    

    【讨论】:

    • 完美:O .. 问题解决了。实际上我知道我必须在 Air 上创建 TextView,但我在没有“实现 OnClickListener”的情况下创建了我的 prgram,然后我就这样走了……我使用了 new TextView(this) 这是我的烂摊子:| stackoverflow.com/questions/23199133/…
    【解决方案3】:

    如果您使用findViewById,则生成的视图已经是您布局的一部分并且有一个父视图。每个视图只能添加到一个 ViewGroup 一次。您需要制作 new TextViews 并将它们添加到您的 LinearLayout。您可以通过 TextView 构造函数或具有单独 xml 布局的 LayoutInflater 来执行此操作。

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 1970-01-01
      • 2020-07-23
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      • 2020-02-21
      • 2021-07-16
      • 1970-01-01
      相关资源
      最近更新 更多