【发布时间】: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 但是非常感谢!