Android LayoutInflater的inflate方法中attachToRoot的作用
我们在ListView的Adapter的getView方法里面经常会调用两个参数的inflate方法,
mInflater.inflate(R.layout.adv_viewpager, null)
我们可能会发现layout外层的layout_width layout_height属性都没起作用,全都变成wrap_content的值了。
这个问题就是因为我们使用了错误的参数照成的
系统在inflate layout的时候 如果传入的root为 空 的话就会 忽略 LayoutParams.
所以在getView里面应该调用
mInflater.inflate(R.layout.adv_viewpager, root, false)
这样在R.layout.adv_viewpager layout xml文件里面所有关于Layout的属性就都能生效。
那么attachToRoot是什么作用呢?
他会自动把layout加到View hierarchy中,不需要手动调用root.addView
当然在Adapter.getView里面不用手动调用root.addView是因为Adapter已经帮我们做了, 所以如果我们在Adapter.getView里面传入attachToRoot为true的话,就会报错
因为一个view不能attach两次。
Reference:
http://www.doubleencore.com/2013/05/layout-inflation-as-intended/
http://lmbj.net/blog/layoutinflater-and-layoutparams/
本文深入解析了在Android ListView Adapter的getView方法中使用inflate方法时,attachToRoot参数的作用及其原理,解释了为何在某些情况下布局属性不起作用,并提供了正确使用的示例。
1395

被折叠的 条评论
为什么被折叠?



