对于我的应用程序,我必须动态创建许多带有复选框和 TextView 的水平线性布局。目前我在 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.
我还考虑过将布局添加到主线性布局,然后获取并复制它,然后再添加更多。你们能帮我学习如何做吗?
非常感谢!
最佳答案
LinearLayout l = (LinearLayout) inflate.inflate(R.layout.inflater, main, false);
我怀疑问题是您将 main
指定为 ViewGroup
参数。
尝试将 attachToRoot
参数设置为 true
,然后删除 main.addView(l)
行。
或者将 ViewGroup
参数设置为 null
并保留 main.addView(l)
行。
关于android - LayoutInflater 添加多个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14025126/