對於LayoutInflater.from(parent.getContext()).inflate()方法的筆記

今天在練習的時候,,發現這裏面兩個方法的區別,給自己做點筆記

第一種,LayoutInflater.from(parent.getContext()) inflate(R.layout.item_layout, null);
第二種,LayoutInflater.from(parent.getContext())inflate(R.layout.item_layout, parent,false); 
item_layout的佈局是這樣的

這兩個都是不會報錯的,但是效果不一樣,
第一種方式LayoutInflater.from(parent.getContext()) inflate(R.layout.item_layout, null);

第二種方式LayoutInflater.from(parent.getContext())inflate(R.layout.item_layout, parent,false); 由上面的結果顯示,裏面的參數 parent ,false着兩個參數的含義,第一個,毋庸置疑,就是這個佈局放在哪兒。就是這個parent這個fasle 所對應的參數,源碼裏面是這麼說的  Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.google了一下,膨脹的層次結構是否應該附加到根參數? 如果爲false,則root僅用於爲XML中的根視圖創建LayoutParams的正確子類。意思就是這個你在子佈局中設置的屬性是否添加到parent,如果設置爲fasle,就是你在xml中設置成什麼樣就是什麼樣了,像上面我寫的match_parent,它就佔據parent的整個頁面,不會再添加,當你設置爲true的時候,他就報錯了,java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first,說是這個頁面已經有一個parent了。同理。當LayoutInflater.from(parent.getContext()) inflate(R.layout.item_layout, parent);的時候,會報同樣的錯。以此做個筆記


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章