国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

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

2019-12-12 02:32:37
字體:
來源:轉載
供稿:網友

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;

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 邯郸市| 新余市| 临高县| 新晃| 辽中县| 门头沟区| 博乐市| 陕西省| 三门县| 兴化市| 宁德市| 南昌县| 通渭县| 宁武县| 肇庆市| 西城区| 霍城县| 富平县| 韶山市| 苏尼特右旗| 沙坪坝区| 海盐县| 略阳县| 翼城县| 彝良县| 海兴县| 界首市| 湘乡市| 宜都市| 宜章县| 南涧| 永新县| 金平| 乌什县| 汉川市| 霍林郭勒市| 拉孜县| 屏南县| 招远市| 鲁山县| 新绛县|