最近在用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); }