Android關於inflate的root參數

來源:互聯網
上載者:User

標籤:

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

 

Android關於inflate的root參數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.