使用android分页库创建通用PagedListAdapter

使用android分页库创建通用PagedListAdapter,android,android-paging,Android,Android Paging,我的应用程序有4个以上不同数据模型的列表。 我想创建一个更通用的CommonAdapter,它扩展了PagedListAdapter 这是我目前的代码 public abstract class CommonPagedListAdapter<T, VH extends RecyclerView.ViewHolder> extends PagedListAdapter<T, VH> { private Context mContext; p

我的应用程序有4个以上不同数据模型的列表。
我想创建一个更通用的
CommonAdapter
,它扩展了
PagedListAdapter

这是我目前的代码

public abstract class CommonPagedListAdapter<T, VH extends RecyclerView.ViewHolder>
        extends PagedListAdapter<T, VH> {

    private Context mContext;
    private ArrayList<T> mArrayList;

    public abstract void onItemClick(T model, int position);
    public abstract int getLayoutResId();

    protected CommonPagedListAdapter(Context context, ArrayList<T> arrayList,
                                     @NonNull DiffUtil.ItemCallback<T> diffCallback) {
        super(diffCallback);
        this.mContext  = context;
        this.mArrayList = arrayList;
    }

    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //what should i return here?
        View view = LayoutInflater.from(mContext).inflate(getLayoutResId(),parent,false);
        return (VH) new ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position) {
        //what should i do here?
//        holder
    }

    class ItemViewHolder extends RecyclerView.ViewHolder {

        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }
}
公共抽象类CommonPagedListAdapter
扩展PagedListAdapter{
私有上下文;
私人ArrayList结婚名单;
公共抽象空间(T模型,int位置);
公共摘要int getLayoutResId();
受保护的CommonPagedListAdapter(上下文上下文、ArrayList、ArrayList、,
@非Null DiffUtil.ItemCallback(diffCallback){
超级(diffCallback);
this.mContext=上下文;
this.mArrayList=arrayList;
}
@非空
@凌驾
公共VH onCreateViewHolder(@NonNull ViewGroup父级,int-viewType){
//我该怎么回这里?
View=LayoutFlater.from(mContext).充气(getLayoutResId(),父项,false);
返回(VH)新项目视图持有者(视图);
}
@凌驾
BindViewHolder上的公共无效(@非空VH holder,内部位置){
//我在这里该怎么办?
//持有者
}
类ItemViewHolder扩展了RecyclerView.ViewHolder{
public ItemViewHolder(@NonNull View itemView){
超级(项目视图);
}
}
}
我正在使用Android分页库中的PagelListAdapter
我想知道几件事:
-由于我将拥有不同的视图持有者,因此在创建视图持有者的
中应该设置什么?
-在BindViewHolder中应该设置什么?

-这真的是使CommonPagedListAdapter可扩展和可维护的正确方法吗?

我遇到了一个类似的问题,我试图创建一个适配器用于多种不同的列表类型。我最终得出的结论是,最好对每种列表类型使用单独的适配器,因为这样可以避免生成一个非常大的“公共”适配器类,这违反了“单一责任”原则。这样,每个适配器都更小、更易于维护和灵活

但是,如果您真的想为类似的项目使用单个适配器,我通常的做法是为每个项目类型创建唯一的viewholder,然后使用switch语句或类似的方法在onBindViewHolder中相应地绑定它们。为了做到这一点,您需要覆盖适配器中名为
getItemViewType
的附加方法


有一个非常好的指南介绍了如何创建一个适配器来处理代码路径上的不同视图类型:

我遇到了一个类似的问题,我试图创建一个适配器来用于多个不同的列表类型。我最终得出的结论是,最好对每种列表类型使用单独的适配器,因为这样可以避免生成一个非常大的“公共”适配器类,这违反了“单一责任”原则。这样,每个适配器都更小、更易于维护和灵活

但是,如果您真的想为类似的项目使用单个适配器,我通常的做法是为每个项目类型创建唯一的viewholder,然后使用switch语句或类似的方法在onBindViewHolder中相应地绑定它们。为了做到这一点,您需要覆盖适配器中名为
getItemViewType
的附加方法

有一个非常好的指南介绍了如何创建一个适配器来处理代码路径上的不同视图类型: