Recycler View 支持多个 pojo 类

Recycler View supporting multiple pojo classes

我有一个要求,我有一个应该由多个模型支持的回收站视图 类。 我的回收站视图将膨胀多个不同的布局。所以为了膨胀布局我定义了我的 onCreateViewholder 如下:

     @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        RecyclerView.ViewHolder viewHolder = null;
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());

        switch (viewType) {
            case 1:
                View v1 = inflater.inflate(R.layout.searchresultsrow1, parent, false);
                viewHolder = new AppViewHolder(v1);
                break;
            case 2:
                View v2 = inflater.inflate(R.layout.searchresultsrow2, parent, false);
                viewHolder = new AppViewHolder(v2);
                break;
         return viewHolder
}

在 bindview 方法中,我使用的实例来确定持有人类型:`

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        if(holder instanceof AppViewHolder){
            AppViewHolder vh1 = (AppViewHolder) holder;
vh1.appName.setText(Html.fromHtml(**appList**.get(position).getmAppName());
}
} else if (holder instanceof ContactViewHolder){
ContactViewHolder vh3 = (ContactViewHolder) holder; vh3.contactName.setText(Html.fromHtml(**contactList**.get(position).getContactName()));}
}`

现在我不知道在 itemCount 上发送什么:

  @Override
    public int getItemCount() {
        return  ??;
    }

由于我的 applist 对象类型不同并且 contact 列表对象类型不同。 我曾尝试在 getItemCount 中使用 switch case,但它仅 returns 单个列表的计数并仅显示特定列表的结果,而我想要两个列表的组合结果 。 如果我发送两个列表的加法,那么我将遇到 arrayindexoutofbounds 异常。 在这种情况下可以使用什么方法?

你可以这样做

@Override
public int getItemCount() {
    if(appList != null && contactList != null)
        return appList.size() + contactList.size();
    else
    {
        if(appList != null)
            return appList.size();
        else if (contactList != null)
            return contactList.size();
        else
            return 0;
    }
}

注意:您必须跟踪从每个列表中呈现的项目数,并使用该索引从相应列表中获取项目,否则您将得到 ArrayIndexOutOfBoundsExcetption.不要使用当前位置从列表中获取项目。

更新

保留两个变量

private int appListIndex = 0;
Private int contactListIndex = 0;

处于 class 级别。

然后这样做

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    if(holder instanceof AppViewHolder){
        AppViewHolder vh1 = (AppViewHolder) holder;
        vh1.appName.setText(Html.fromHtml(appList.get(appListIndex++).getmAppName());
    }
    } else if (holder instanceof ContactViewHolder){
        ContactViewHolder vh3 = (ContactViewHolder) holder;     
        vh3.contactName.setText(Html.fromHtml(contactList.get(contactListIndex++).getContactName()));
    }
}

i want results combined of both the list:

由于您希望两个列表都在 recyclerView 中产生结果,因此创建一个对象类型的列表并将两个列表的所有内容添加到此列表中。然后在 onBindViewHolder() 中检查 list.get(position) instanceOf YourClass 然后根据类型进行操作。

In getItemCount() return 组合列表的大小。

希望对您有所帮助。