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

首頁(yè) > 系統(tǒng) > Android > 正文

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

2019-10-22 18:33:01
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

RecyclerView顯示Item布局不一致

在自定義RecyclerAdapter的時(shí)候,在重寫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的時(shí)候發(fā)現(xiàn),LayoutParams是由于ViewGroup生成的,因?yàn)檫@里添加的ViewGroup為null。所以并不會(huì)生成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方法實(shí)現(xiàn)如下。

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

最終會(huì)造成RecycleView的顯示效果與布局文件不一致。后來(lái)使用了LayoutInflater來(lái)填充布局。

@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的話就不會(huì)將生成的View添加到parent。但是會(huì)根據(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.

因?yàn)樵趏nCreateViewHolder中產(chǎn)生的View不能由我們手動(dòng)添加到RecycleView中所以最后的參數(shù)只能是false;

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


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到Android開發(fā)頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 泰顺县| 永济市| 乌海市| 西林县| 双鸭山市| 盐城市| 乐平市| 黔江区| 泰顺县| 烟台市| 平南县| 姚安县| 柘城县| 绥棱县| 磴口县| 文昌市| 桃园市| 方正县| 翼城县| 徐州市| 正宁县| 德昌县| 渝中区| 东乌珠穆沁旗| 南平市| 中超| 关岭| 高邑县| 平定县| 铁力市| 土默特左旗| 延安市| 贵定县| 祥云县| 德安县| 定兴县| 缙云县| 登封市| 冷水江市| 邮箱| 淮南市|