[英]Paging library - one recycler with multiple view types
I am using all Android architecture components in my project (Room DB, Live Data etc.) Currently, I am facing a problem that I have RecyclerView which should used loaded data from Room DB and display it with Paging library. 我在我的项目中使用所有Android架构组件(Room DB,Live Data等)。目前,我遇到的问题是我有RecyclerView,它应该使用来自Room DB的加载数据并使用Paging库显示它。 The problem is that there is a multiple data classes which represents the items in newsfeed and are stored in Room and I need display them in that one recycler.
问题是有多个数据类代表新闻源中的项目并存储在Room中,我需要在那个回收器中显示它们。
Is there any way how to easily solve it? 有什么办法可以轻松解决吗? Can I for example create some interface which would be used by all these classes?
我可以创建一些可供所有这些类使用的接口吗?
You can provide multiple View holder to list by overriding getItemViewType() method of RecyclerView.Adapter. 您可以通过覆盖RecyclerView.Adapter的getItemViewType()方法来提供多个View holder列表。
Code Snippet 代码片段
@Override
public int getItemViewType(int position) {
// Just as an example, return 0 or 2 depending on position
// Note that unlike in ListView adapters, types don't have to be contiguous
return position % 2 * 2;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0: return new ViewHolder0(...);
case 2: return new ViewHolder2(...);
...
}
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
switch (holder.getItemViewType()) {
case 0:
ViewHolder0 viewHolder0 = (ViewHolder0)holder;
...
break;
case 2:
ViewHolder2 viewHolder2 = (ViewHolder2)holder;
...
break;
}
}
You could create and interface 你可以创建和界面
public interface NeewsFeedItem
String getTitle();
int getType();
String data();
...
Each of your model implement NeewsFeedItem
and inside your Adapter you decide what type of view to show and how to show the proper NeewsFeedItem
. 您的每个模型都
implement NeewsFeedItem
,在您的适配器中,您可以决定要显示的视图类型以及如何显示正确的NeewsFeedItem
。
You could override getItemViewType to show different presentation for different NeewsFeed's types. 您可以覆盖getItemViewType以显示不同NeewsFeed类型的不同表示。
Also you could check FlexibleAdapter library that could help to manage your adapter with different types, headers, footers etc. 您还可以查看FlexibleAdapter库,它可以帮助您管理具有不同类型,页眉,页脚等的适配器。
I wanted to add header to recyclerView. 我想将标题添加到recyclerView。 Couldn't have different item type for first position, as library after reloading items caused recyclerview to scroll all way down to bottom of list.
第一个位置不能有不同的项目类型,因为重新加载项目后的库会导致recyclelerview一直向下滚动到列表的底部。
I have created ViewHolder that holds my regular list item plus my header. 我创建了ViewHolder,它包含我的常规列表项和我的标题。 This way my regular item was on position 0 with header, library stopped scrolling to bottom of recyclerView as first item was pagination's item aswell.
这样我的常规项目在头部0的位置,库停止滚动到recyclerView的底部,因为第一项是分页的项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.