Android关于inflate的root参数
最近在用View inflate(Context context, int resource, ViewGroup root)方法时,在第三个参数root上碰到了点麻烦。
一般在写ListView的adapter时,会这样加载自定义列
View imageLayout = inflate(getContext(),R.layout.item_album_pager, null); ... viewGroup.addView(imageLayout);
如果这样写,调用imageLayout时就可能出问题
//在inflate时就把layout加入viewGroup View imageLayout = inflate(getContext(),R.layout.item_album_pager, viewGroup);
这是由于,inflate方法在第三个参数root不为空时,返回的View就是root,而当root为空时,返回的才是加载的layout的根节点。看api解释:
Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error. Parameters: resource ID for an XML layout resource to load (e.g., R.layout.main_page) root Optional view to be the parent of the generated hierarchy. Returns: The root View of the inflated hierarchy. If root was supplied, this is the root View; otherwise it is the root of the inflated XML file.
本人便是在ViewPager的adapter中,使用了root不为空的inflate方法,在返回layout时出错了。
@Override public Object instantiateItem(ViewGroup viewGroup, int position) { View imageLayout = inflate(getContext(),R.layout.item_album_pager, viewGroup); .... //这里实际上把整个viewGroup返回了,导致出错 return imageLayout; }
这里举例的是View类自带的inflate方法,它本质调用的就是LayoutInflater类的 View inflate(int resource, ViewGroup root)方法。
public static View inflate(Context context, int resource, ViewGroup root) { LayoutInflater factory = LayoutInflater.from(context); return factory.inflate(resource, root); }