欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android RecyclerView顯示Item布局不一致解決辦法

 更新時間:2017年07月04日 11:41:54   投稿:lqh  
這篇文章主要介紹了Android RecyclerView顯示Item布局不一致解決辦法的相關(guān)資料,需要的朋友可以參考下

RecyclerView顯示Item布局不一致

在自定義RecyclerAdapter的時候,在重寫onCreateViewHolder方法是使用了

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

進(jìn)行生成布局,結(jié)果發(fā)現(xiàn)生成的布局沒有LayoutParams。以前自定義View的時候發(fā)現(xiàn),LayoutParams是由于ViewGroup生成的,因為這里添加的ViewGroup為null。所以并不會生成LayoutParams。結(jié)果在RecyclerView的getViewForPosition方法中檢查了有沒有LayoutParams如果沒有的話就調(diào)用LayoutManager的generateDefaultLayoutParams生成默認(rèn)的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中g(shù)enerateDefaultLayoutParams方法實現(xiàn)如下。

/**
   * {@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源碼發(fā)現(xiàn)inflate最后的參數(shù)如果是false的話就不會將生成的View添加到parent。但是會根據(jù)parent產(chǎn)生相應(yīng)的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中產(chǎn)生的View不能由我們手動添加到RecycleView中所以最后的參數(shù)只能是false;

 感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

相關(guān)文章

最新評論