已停止更新,点击跳往独立博客
想要实现如下效果只需要一个recyclerView里面一个textView即可。
Adapter 代码
static class MyAdapter extends RecyclerView.Adapter {
private Context mContext;
private List mStrings = new ArrayList<>();
public MyAdapter(Context context) {
mContext = context;
for (int i = 0; i < 20; i++) {
mStrings.add("" + i);
}
}
@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_list, null);
return new MyHolder(view);
}
@Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.mTextView.setText(mStrings.get(position));
}
@Override
public int getItemCount() {
return mStrings.size();
}
static class MyHolder extends RecyclerView.ViewHolder {
TextView mTextView;
public MyHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.text);
}
}
}
xml文件如下:
可是实现的效果是这样的
可以看到宽明明是match _ parent但是在这里却变成了wrap_content,即文本长度多长,textView宽度都宽,为什么会失效呢?
首先一个View的宽高padding什么的失我第一个想到的就是LayoutParams,因为一些xml里面属性都在LayoutParams里面,如果失效了估计是LayoutParams没有set上去。
LayoutInflater.from(mContext).inflate(R.layout.item_list, null);
LayoutInflater.from(mContext).inflate(R.layout.item_list,parent, false);
以上是最为普通使用LayoutInflater加载Layout方式,上面的列子中如果使用了3个参数的方法来加载Layout,也就解决了宽度问题,搞懂了2个参数和3个参数方法的区别也就明白了。
代码如下
@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_list, parent, false);
return new MyHolder(view);
}
如上也就解决了宽度失效问题,可是为什么呢?
源码
/**
* Inflate a new view hierarchy from the specified xml resource. Throws
* {@link InflateException} if there is an error.
*
* @param resource ID for an XML layout resource to load (e.g.,
* R.layout.main_page
)
* @param root Optional view to be the parent of the generated hierarchy.
* @return The root View of the inflated hierarchy. If root was supplied,
* this is the root View; otherwise it is the root of the inflated
* XML file.
*/
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
本质上2个参数的方法也是调用了3个参数的方法。
三个参数源码如下
/**
* Inflate a new view hierarchy from the specified xml resource. Throws
* {@link InflateException} if there is an error.
*
* @param resource ID for an XML layout resource to load (e.g.,
* R.layout.main_page
)
* @param root Optional view to be the parent of the generated hierarchy (if
* attachToRoot is true), or else simply an object that
* provides a set of LayoutParams values for root of the returned
* hierarchy (if attachToRoot is false.)
* @param attachToRoot Whether the inflated hierarchy should be attached to
* the root parameter? If false, root is only used to create the
* correct subclass of LayoutParams for the root view in the XML.
* @return The root View of the inflated hierarchy. If root was supplied and
* attachToRoot is true, this is root; otherwise it is the root of
* the inflated XML file.
*/
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) + ")");
}
//解析xml
final XmlResourceParser parser = res.getLayout(resource);
try {
//inflate的地方
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
/**
* Inflate a new view hierarchy from the specified XML node. Throws
* {@link InflateException} if there is an error.
*
* Important For performance
* reasons, view inflation relies heavily on pre-processing of XML files
* that is done at build time. Therefore, it is not currently possible to
* use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
*
* @param parser XML dom node containing the description of the view
* hierarchy.
* @param root Optional view to be the parent of the generated hierarchy (if
* attachToRoot is true), or else simply an object that
* provides a set of LayoutParams values for root of the returned
* hierarchy (if attachToRoot is false.)
* @param attachToRoot Whether the inflated hierarchy should be attached to
* the root parameter? If false, root is only used to create the
* correct subclass of LayoutParams for the root view in the XML.
* @return The root View of the inflated hierarchy. If root was supplied and
* attachToRoot is true, this is root; otherwise it is the root of
* the inflated XML file.
*/
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
... 省略部分代码
if (DEBUG) {
System.out.println("**************************");
System.out.println("Creating root view: "
+ name);
System.out.println("**************************");
}
// 判断是否是merge标签
if (TAG_MERGE.equals(name)) {
if (root == null || !attachToRoot) {
throw new InflateException(" can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
rInflate(parser, root, inflaterContext, attrs, false);
} else {
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
// 关键点
ViewGroup.LayoutParams params = null;
// parent 是否为空
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// Create layout params that match root, if supplied
// 创建跟布局的LayoutParams
params = root.generateLayoutParams(attrs);
// 是否为false 如果是flase则添加到view里面
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 against its context.
rInflateChildren(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.
// 注意到这里如果是true 则会将其View添加到root里面
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;
}
}
... 省略部分代码
return result;
}
}
注意看到判断是否MERGE的else分支,里面关键的地方都已经写上注释。
其实也就是说,如果root不是空的话,回去创建LayoutParams,在判断如果attchToRoot参数如果是false,则会setLayoutParams到View里面去。
文章的开头有说到LayoutParams这个类,里面都是一个在xml声明的属性,那我们尝试的从侧门解决一下问题,看如下代码
@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_list, null);
view.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
return new MyHolder(view);
}
我手动为其设置了LayoutParams,结果如何呢?如下
一样的。
这是因为RecyclerView里面机制如果LayoutParams是空的会给一个默认的LayoutParams。以后有兴趣贴源码。
// 只会生成View 并不会设置任何属性
LayoutInflater.from(mContext).inflate(R.layout.item_list, null);
// 如果parent不为空会为其生成LayoutParams属性,
// attchToRoot如果为flase则会将LayoutParams Set进去,如果为true,则会添加到root里面
LayoutInflater.from(mContext).inflate(R.layout.item_list,parent, false);
这种问题其实在开发中非常常见不过当时解决了之后并没有深究其原因实属不该。