2012-12-24 56 views
3

对于我的应用程序,我必须动态创建与复选框和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,然后得到它,复制它,然后添加更多。你们能否帮我学习如何做到这一点?

非常感谢!

+0

为什么你不能把它放在任何类型的循环中? –

+0

对不起,我已经包含了我的logcat。 – AndroidPenguin

+0

如果您在循环中设置线性布局的ID,即l.setId(i) – jnthnjns

回答

5
LinearLayout l = (LinearLayout) inflate.inflate(R.layout.inflater, main, false); 

我怀疑问题是您指定main作为ViewGroup参数。

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

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

+2

第一个解决方案导致没有错误,但只添加了一个视图。第二个完美的工作! :D – AndroidPenguin

+0

@AndroidPenguin:很高兴帮助 - 我想他们中的一个会工作,但不能完全记得,因为我做了这样的事情已经有一段时间了。 – Squonk

+0

我不能相信这是一个简单的解决方案,我认为我必须彻底关闭或什么:P真的很感谢Squonk的帮助。 :) – AndroidPenguin