今天,看到了一篇文章講LayoutInflater的用法,瞬間感覺自己對這個類確實不夠了解,於是簡單的看了下LayoutInflater類的源代碼,對這個類有了新的認識。
首先,LayoutInflater這個類是用來幹嘛的呢?
我們最常用的便是LayoutInflater的inflate方法,這個方法重載了四種調用方式,分別爲:
1. public View inflate(int resource, ViewGroup root)
2. public View inflate(int resource, ViewGroup root, boolean attachToRoot)
3.public View inflate(XmlPullParser parser, ViewGroup root)
4.public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)
這四種使用方式中,我們最常用的是第一種方式,inflate方法的主要作用就是將xml轉換成一個View對象,用於動態的創建佈局。雖然重載了四個方法,但是這四種方法最終調用的,還是第四種方式。第四種方式也很好理解,內部實現原理就是利用Pull解析器,對Xml文件進行解析,然後返回View對象。inflate方法有三個參數,分別是
1.resource佈局的資源id
2.root填充的根視圖
3.attachToRoot是否將載入的視圖綁定到根視圖中
在這個例子中,我們將root參數設爲空,功能確實實現了,但是這裏還隱藏着一個隱患,這種方式並不是inflate正確的使用姿勢,下面我們通過一個Demo,來說一下這樣使用造成的弊端。
我們以我們經常使用的第一種形式爲例,你在重寫BaseAdapter的getView方法的時候是否這樣做過
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflate(R.layout.item_row, null);
}
return convertView;
}
inflate方法有三個參數,分別是
1.resource佈局的資源id
2.root填充的根視圖
3.attachToRoot是否將載入的視圖綁定到根視圖中
在這個例子中,我們將root參數設爲空,功能確實實現了,但是這裏還隱藏着一個隱患,這種方式並不是inflate正確的使用姿勢,下面我們通過一個Demo,來說一下這樣使用造成的弊端。
首先,我們建立一個這樣的項目這裏三個界面,一個主界面,兩個測試界面,佈局文件中,主界面只負責界面跳轉,兩個測試界面都是一個簡單的Listview,item佈局顯示效果如下
對應的佈局文件如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="@android:color/holo_orange_light"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="11"
android:textColor="@android:color/black"
android:textSize="22sp" />
</LinearLayout>
OneActivity的代碼如下
public class OneActivity extends Activity {
private ListView list1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
list1 = (ListView) findViewById(R.id.list1);
list1.setAdapter(new MyAdapter(this));
}
private class MyAdapter extends BaseAdapter {
private LayoutInflater inflater;
MyAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return 20;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_list, null);
}
TextView tv = (TextView) convertView.findViewById(R.id.tv);
tv.setText(position+"");
return convertView;
}
}
}
TwoActivity的代碼如下
public class TwoActivity extends Activity {
private ListView list2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
list2 = (ListView) findViewById(R.id.list2);
list2.setAdapter(new MyAdapter(this));
}
private class MyAdapter extends BaseAdapter {
private LayoutInflater inflater;
MyAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return 20;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_list, parent,false);
}
TextView tv = (TextView) convertView.findViewById(R.id.tv);
tv.setText(position + "");
return convertView;
}
}
}
兩個文件最關鍵的區別就一句話,
在getView方法中,OneActivity是
convertView = inflater.inflate(R.layout.item_list, null);
在getView方法中,TwoActivity是
convertView = inflater.inflate(R.layout.item_list, parent,false);
我們先看一下顯示效果,再說兩者的區別
OneActivity效果
TwoActivity的顯示效果
我們可以很明顯的看出來,使用第一種方式,根佈局的高度設置60dp沒有起作用,系統還是按照包裹內容的方式加載的,爲什麼會產生這種效果呢?我們從需要inflate方法的源代碼中找一下答案。
首先,方式一的源代碼實現
public View inflate(XmlPullParser parser, ViewGroup root) {
return inflate(parser, root, root != null);
}
當我們使用方式一,並且第二個參數傳入null的時候,默認調用的是下面的方法,並且attachToRoot是false public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
if (DEBUG) System.out.println("INFLATING from resource: " + resource);
XmlResourceParser parser = getContext().getResources().getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
在這一個方法中,pull解析器將資源id轉化成XmlResourceParser對象,又傳給了第四種方式,所以我們需要重點看的還是第四種方式是如何實現的
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context)mConstructorArgs[0];
mConstructorArgs[0] = mContext;
View result = root;
try {
// Look for the root node.
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
final String name = parser.getName();
if (DEBUG) {
System.out.println("**************************");
System.out.println("Creating root view: "
+ name);
System.out.println("**************************");
}
if (TAG_MERGE.equals(name)) {
if (root == null || !attachToRoot) {
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
rInflate(parser, root, attrs, false);
} else {
// Temp is the root view that was found in the xml
View temp;
if (TAG_1995.equals(name)) {
temp = new BlinkLayout(mContext, attrs);
} else {
temp = createViewFromTag(root, name, attrs);
}
ViewGroup.LayoutParams params = null;
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// Create layout params that match root, if supplied
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
if (DEBUG) {
System.out.println("-----> start inflating children");
}
// Inflate all children under temp
rInflate(parser, temp, attrs, true);
if (DEBUG) {
System.out.println("-----> done inflating children");
}
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// Decide whether to return the root that was passed in or the
// top view found in xml.
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
InflateException ex = new InflateException(e.getMessage());
ex.initCause(e);
throw ex;
} catch (IOException e) {
InflateException ex = new InflateException(
parser.getPositionDescription()
+ ": " + e.getMessage());
ex.initCause(e);
throw ex;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
}
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
return result;
}
}
代碼比較長,我們重點關注下面的代碼
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// Create layout params that match root, if supplied
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
這些代碼的意思就是,當我們傳進來的root參數不是空的時候,並且attachToRoot是false的時候,也就是上面的TwoActivity的實現方式的時候,會給temp設置一個LayoutParams參數。那麼這個temp又是幹嘛的呢?
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// Decide whether to return the root that was passed in or the
// top view found in xml.
if (root == null || !attachToRoot) {
result = temp;
}
現在應該明白了吧,當我們傳進來的root不是null,並且第三個參數是false的時候,這個temp就被加入到了root中,並且把root當作最終的返回值返回了。而當我們設置root爲空的時候,沒有設置LayoutParams參數的temp對象,作爲返回值返回了。
因此,我們可以得出下面的結論:
1.若我們採用convertView = inflater.inflate(R.layout.item_list, null);方式填充視圖,item佈局中的根視圖的layout_XX屬性會被忽略掉,然後設置成默認的包裹內容方式
2.如果我們想保證item的視圖中的參數不被改變,我們需要使用convertView = inflater.inflate(R.layout.item_list, parent,false);這種方式進行視圖的填充
3.除了使用這種方式,我們還可以設置item佈局的根視圖爲包裹內容,然後設置內部控件的高度等屬性,這樣就不會修改顯示方式了。