欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

Android RecyclerView显示Item布局不一致解决办法

时间:2021-06-10 08:23:19|栏目:Android代码|点击:

RecyclerView显示Item布局不一致

在自定义RecyclerAdapter的时候,在重写onCreateViewHolder方法是使用了

 @Override
  public H onCreateViewHolder(ViewGroup parent, int viewType) {
    View view=View.inflate(context,layoutId,null);
    return view;
  }

进行生成布局,结果发现生成的布局没有LayoutParams。以前自定义View的时候发现,LayoutParams是由于ViewGroup生成的,因为这里添加的ViewGroup为null。所以并不会生成LayoutParams。结果在RecyclerView的getViewForPosition方法中检查了有没有LayoutParams如果没有的话就调用LayoutManager的generateDefaultLayoutParams生成默认的LayoutParames。代码段如下:

 final ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
      final LayoutParams rvLayoutParams;
      if (lp == null) {
        rvLayoutParams = (LayoutParams) generateDefaultLayoutParams();
        holder.itemView.setLayoutParams(rvLayoutParams);
      } else if (!checkLayoutParams(lp)) {
        rvLayoutParams = (LayoutParams) generateLayoutParams(lp);
        holder.itemView.setLayoutParams(rvLayoutParams);
      } else {
        rvLayoutParams = (LayoutParams) lp;
      }

而在LinearLayoutManager中generateDefaultLayoutParams方法实现如下。

/**
   * {@inheritDoc}
   */
  @Override
  public LayoutParams generateDefaultLayoutParams() {
    return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT);
  }

最终会造成RecycleView的显示效果与布局文件不一致。后来使用了LayoutInflater来填充布局。

@Override
  public H onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = mInflater.inflate(layoutId, parent, false);
    return getInstanceOfH(view);
  }

查看LayoutInflater源码发现inflate最后的参数如果是false的话就不会将生成的View添加到parent。但是会根据parent产生相应的LayoutParams 。源码如下:

* @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.

因为在onCreateViewHolder中产生的View不能由我们手动添加到RecycleView中所以最后的参数只能是false;

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

上一篇:Android开发中include控件用法分析

栏    目:Android代码

下一篇:Flutter开发之设置应用名称及图标的教程

本文标题:Android RecyclerView显示Item布局不一致解决办法

本文地址:http://www.codeinn.net/misctech/139035.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有