LayoutInflater添加多个视图

And*_*uin 3 android layout-inflater

对于我的应用程序,我必须动态创建一些带有复选框和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);
Run Code Online (Sandbox Code Playgroud)

问题是我不能把它放在任何类型的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.
Run Code Online (Sandbox Code Playgroud)

我还考虑将布局添加到主线性布局,然后获取它并复制它然后添加更多.你们可以帮我学习怎么做吗?

非常感谢你!

Squ*_*onk 5

LinearLayout l = (LinearLayout) inflate.inflate(R.layout.inflater, main, false);
Run Code Online (Sandbox Code Playgroud)

我怀疑问题是你指定mainViewGroup参数.

尝试设置attachToRoot参数true然后删除该main.addView(l)行.

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

  • 第一个解决方案没有错误,但只添加了一个视图.第二个完美!:d (2认同)