如何使用listview实现具有异构行类型(图像视频和文本)的聊天列表视图?

时间:2015-06-20 06:23:28

标签: android android-listview chat android-recyclerview

我正在构建一个正常的聊天应用程序。可以发送图像,文本和视频,因此我的列表中需要多种行样式。我使用listview。但是Listview多次返回(在回收行之后)错误的行并且我的尝试失败了。任何想法怎么做?可以使用RecyclerView完成吗? 感谢。

1 个答案:

答案 0 :(得分:5)

可以使用recyclerview完成。以下是我在单个recyclerview中显示多种行的方法

// Different types of rows
private static final int TYPE_ITEM1 = 0;
private static final int TYPE_ITEM2 = 1;

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
class ViewHolder0 extends RecyclerView.ViewHolder {
    // Viewholder for row type 0
}

class ViewHolder1 extends RecyclerView.ViewHolder {
    // Viewholder for row type 1
}

@Override
public int getItemViewType(int position) {
    // Here you have to write logic for which position have which type of row and return the same
    if (position == 0) {
        return TYPE_ITEM0;
    } else {
        return TYPE_ITEM1;
    }
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
     switch (viewType) {
         case 0: return new ViewHolder0(LayoutInflater.from(viewGroup.getContext())
                        .inflate(R.layout.itme0, viewGroup, false););
         case 1: return new ViewHolder1(LayoutInflater.from(viewGroup.getContext())
                        .inflate(R.layout.item1, viewGroup, false););
         ...
     }
}

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, int position) {
     if (viewHolder.getItemViewType() == TYPE_ITEM0) {
         // Code to populate type 0 view here
     } else if (viewHolder.getItemViewType() == TYPE_ITEM1) {
         // code to populate type 1 view here
     }
}