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);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM