RecycleView添加條目佈局match_parent失效的問題

RecycleView在使用過程中遇到的問題:
1如果使用View view = View.inflate(context, R.layout.list_item, null);這個方式添加條目佈局,佈局中的match_parent失效.
之後將其改成View view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);就可以了.
2通過扒源碼發現LayoutInflater.from(context)方法中通過調用LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);方法返回對象.通過上下文調用getSystemService()方法,傳入”layout_inflater”參數;
public static LayoutInflater from(Context context) {
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null) {
throw new AssertionError(“LayoutInflater not found.”);
}
return LayoutInflater;
}
該方法是Context類下的一個方法.具體實現是通過ContextThemeWrapper類中的方法實現的,通過判斷是否是layout_inflat來返回對象
@Override public Object getSystemService(String name) {
if (LAYOUT_INFLATER_SERVICE.equals(name)) {
if (mInflater == null) {
mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this);
}
return mInflater;
}
return getBaseContext().getSystemService(name);
}
這樣增加了代碼的擴展性,mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this);
cloneInContext()方法是抽象方法,在public final class AsyncLayoutInflater類中private static class BasicInflater extends LayoutInflater
中具體實現的
@Override
public LayoutInflater cloneInContext(Context newContext) {
return new BasicInflater(newContext);
}
最後返回的是子類對象,之後在調用inflate()方法
但子類沒有inflate方法,所以調用父類的LayoutInflater中的方法.
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, “INFLATING from resource: \”” + res.getResourceName(resource) + “\” (”
+ Integer.toHexString(resource) + “)”);
}

final XmlResourceParser parser = res.getLayout(resource);
try {
    return inflate(parser, root, attachToRoot);
} finally {
    parser.close();
}

}
之後在調用重載方法inflate(parser, root, attachToRoot);返回view對象.
所以LayoutInflater顯示通過使用想下文獲取一個子類對象,再通過子類調用的inflate方法,獲取View對象.

發佈了39 篇原創文章 · 獲贊 25 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章