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/