Android RecyclerView能否使用非容器视图作为列表项而非容器布局?
关于RecyclerView列表项使用根布局的问题
首先明确:完全可以用
为什么会抛出异常?
你使用的inflate代码:
final View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.dialog_locker_open_item, parent, true);
第三个参数传true,意味着LayoutInflater会直接把
正确的用法
把inflate的第三个参数改为false即可:
final View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.dialog_locker_open_item, parent, false);
这样LayoutInflater会解析
补充说明
- 使用
作为列表项根布局的核心价值是减少冗余的布局层级(比如你原来的LinearLayout就可以省去),在列表项数量较多时能提升布局渲染性能。 - 只要确保inflate时不直接将
的子视图附加到RecyclerView,就可以正常使用这种写法,完全符合RecyclerView的容器特性。
内容的提问来源于stack exchange,提问作者Heisenberg
相关产品推荐
相关产品推荐

