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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章