Android載入佈局檔案的兩種方式及區別。
阿新 • • 發佈:2019-02-04
第一種
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
inflater.inflate(...);//有多種建構函式
第二種
View inflate(Context context, int resource, ViewGroup root)
下面是應用在ListView中的效果:
效果一
這三種寫法的效果是一樣的,單純的將佈局塞到listview裡面,所以根節點的屬性並沒有被使用,比如layout_width、layout_height以及layout_margin等等:LayoutInflater inflater = LayoutInflater.from(parent.getContext()); inflater.inflate(R.layout.list_item, null); inflater.inflate(R.layout.list_item, null,false); View.inflate(context,R.layout.list_item,null);
效果二
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
inflater.inflate(R.layout.list_item, parent, false);
這種寫法是給你的佈局根節點加了一個根節點,所以你的根節點上的屬性都會得到體現。
其他寫法:
這幾種寫法是一樣的效果,不適用於listview,會出錯,一般不做使用。LayoutInflater inflater = LayoutInflater.from(parent.getContext()); inflater.inflate(R.layout.list_item, parent, false); inflater.inflate(R.layout.list_item, parent); inflater.inflate(R.layout.list_item, parent, true); View.inflate(context,R.layout.list_item,parent);