本文主要介绍RecyclerView实现多种效果,以聊天界面为例。
原理
- getItemViewType(): 获取每一个item的类型,这里面每一个item的类型是自己定制的,可以有一种,也可以有多种。
- onCreateViewHolder(): 针对不同类型的item来创建不同类型的viewholder从而inflate不同的layout
- onBindViewHolder(): 针对不同类型的viewholder来绑定不同的数据
这个例子处理办法是将数据封装为bean,bean中包含item的type,在创建viewholder绑定数据的时候再判断就可以了。
public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final String TAG = "ChatAdapter";
private Context context;
private LayoutInflater inflater;
private List<ChatBean> items = new ArrayList<>();
public ChatAdapter(Context context){
this.context = context;
inflater = LayoutInflater.from(context);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == ChatBean.TYPE_RIGHT) {
View view = inflater.inflate(R.layout.item_chat_right, parent, false);
RightHolder rightHolder = new RightHolder(view);
return rightHolder;
}else if (viewType == ChatBean.TYPE_LEFT){
View v = inflater.inflate(R.layout.item_chat_left,parent,false);
LeftHolder leftHolder = new LeftHolder(v);
return leftHolder;
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof RightHolder) {
RightHolder rightHolder = (RightHolder) holder;
if (items != null) {
rightHolder.tvChatContent.setText(items.get(position).getText());
rightHolder.imgChatHead.setImageURI(Uri.parse(items.get(position).getHeadUrl()));
}
}else if (holder instanceof LeftHolder){
LeftHolder leftHolder = (LeftHolder) holder;
if (items!=null){
leftHolder.tvChatContent.setText(items.get(position).getText());
}
}
}
@Override
public int getItemCount() {
if (items!=null)
return items.size();
else
return 0;
}
@Override
public int getItemViewType(int position) {
return items.get(position).getType();
}
public void addMsg(ChatBean msg){
items.add(msg);
notifyItemInserted(items.size());
}
public class RightHolder extends RecyclerView.ViewHolder {
private TextView tvChatContent;
private SimpleDraweeView imgChatHead;
public RightHolder(View itemView) {
super(itemView);
tvChatContent = (TextView) itemView.findViewById(R.id.tv_chat_right);
imgChatHead = (SimpleDraweeView) itemView.findViewById(R.id.img_chat_head_right);
}
}
public class LeftHolder extends RecyclerView.ViewHolder {
private TextView tvChatContent;
private SimpleDraweeView imgChatHead;
public LeftHolder(View itemView) {
super(itemView);
tvChatContent = (TextView) itemView.findViewById(R.id.tv_chat_left);
imgChatHead = (SimpleDraweeView) itemView.findViewById(R.id.img_chat_head_left);
}
}
}