【问题标题】:LayoutInflater to add multiple viewsLayoutInflater 添加多个视图
【发布时间】:2012-12-24 19:40:27
【问题描述】:

对于我的应用程序,我必须动态创建许多带有复选框和文本视图的水平线性布局。目前我在 for 循环中动态创建这些。为了性能和易用性,我认为使用 layoutinflater 会是一种更好的方法,因此使用正确的格式定义一个水平线性布局,然后将它们添加到某种循环中,但是我遇到了麻烦。如果有更好的方法来实现我所追求的,我也持开放态度(或者我目前的方法确实对性能更好等)

//my main layout
LinearLayout main = (LinearLayout) findViewById(R.id.main);
LayoutInflater inflate = getLayoutInflater();
//inflating the layout containing the horizontal
LinearLayout l = (LinearLayout) inflate.inflate(R.layout.inflater, main, false);
//adding the view
main.addView(l);

问题是我不能把它放在任何类型的 for 循环中。以下是重复 addView 命令的错误日志。

12-24 19:37:18.668: E/AndroidRuntime(8780): java.lang.RuntimeException: Unable
to start activity ComponentInfo{com.example.test1/com.example.test1.MainActivity}: 
java.lang.IllegalStateException: The specified child already has a 
parent. You must call removeView() on the child's parent first.

我还考虑将布局添加到主线性布局,然后获取它并复制它,然后添加更多。你们能帮我学习如何做到这一点吗?

非常感谢!

【问题讨论】:

  • 你为什么不能把它放在任何类型的循环中?
  • 抱歉,我已经包含了我的 logcat。
  • 如果在循环中设置线性布局的id,即l.setId(i)
  • 顺便说一句 - 通常将 cmets 放在您正在评论的代码行上,而不是 放在 下面
  • @Asok,我已经确定布局方向是我修复的第一件事,因为我之前遇到过这个问题:P 但是非常感谢!

标签: android layout-inflater


【解决方案1】:
LinearLayout l = (LinearLayout) inflate.inflate(R.layout.inflater, main, false);

我怀疑问题在于您将main 指定为ViewGroup 参数。

尝试将attachToRoot 参数设置为true,然后删除main.addView(l) 行。

或者将ViewGroup 参数设置为null 并保留main.addView(l) 行。

【讨论】:

  • 第一个解决方案没有导致错误,但只添加了一个视图。第二个工作完美! :D
  • @AndroidPenguin :很高兴能提供帮助 - 我认为其中一个可以工作,但我记不清了,因为我已经有一段时间没有做这样的事情了。
  • 我不敢相信这是一个简单的解决方案,我认为我必须完全关闭或其他东西:P 非常感谢 Squonk 的帮助。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-27
  • 1970-01-01
  • 2015-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多