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对象.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值