您的位置:首页 > 移动开发 > Android开发

Android LayoutInflater的inflate方法中attachToRoot的作用

2015-10-10 10:58 585 查看

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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: