对于我的应用程序,我必须动态创建与复选框和textviews的水平linearlayouts数量。目前我在for循环内动态创建这些。为了性能和易用性,我认为使用layoutinflater会是一种更好的方式来实现这一点,因此定义一个具有正确格式的水平线性布局,然后在某种循环内添加这些布局,但是我遇到了这个问题。我也开到是否有实现的东西我以后是更好的方式(或者,如果我现在的路确实是更好的性能等)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);
问题是我不能把这个在一对任何类型的循环。以下是重复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,然后得到它,复制它,然后添加更多。你们能否帮我学习如何做到这一点?
非常感谢!
为什么你不能把它放在任何类型的循环中? –
对不起,我已经包含了我的logcat。 – AndroidPenguin
如果您在循环中设置线性布局的ID,即l.setId(i) – jnthnjns