Android inflate view的兩種方式

Android inflate view的兩種方式,View.inflate(Context context, @LayoutRes int resource, ViewGroup root)和LayoutInflater.from(context).inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)。
乍一看這兩種方式實現的效果都同樣,View.inflate的方法更簡潔,那麼這兩種方式有什麼區別嗎?
此次要說的重點就在這裏,這裏面有一個坑,好比在寫列表的adapter時,一般要爲item的初始化一個view,這時若是用View.inflate的話,是不能填ViewGroup root,得要寫null,否則會拋異常:The specified child already has a parent. You must call removeView() on the child's parent first.。這裏點開源碼咱們能夠看到,inflate(resource, root, root != null);的第三個參數是否附加於該root,這個參數應該填false。佈局

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
    }

那填了null以後就能夠了嗎,運行跑起來,有些狀況下是view是正常的,但這裏有個坑,View.inflate的時候沒有填ViewGroup root,item的視圖得不到父類view的信息,尺寸可能會有問題,除非item的佈局把尺寸寫死,不過這樣並很差。
這裏推薦在初始化view的時候,使用LayoutInflater.from(context).inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)方法,這種傳遞的信息全面,能夠本身填attachToRoot,不會出現上面那個坑。.net

相關文章
相關標籤/搜索