新建MessageAdapter类继承RecyclerView.Adapter。
public class MessageAdapter extends RecyclerView.Adapter<MessageHolder> {
private int RESOURCE_ID = R.layout.app_list_item_message;
private List<Message> dataList = new ArrayList<>();
private Context context;
@Override
public MessageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
View rootView = View.inflate(context, RESOURCE_ID, null);
return new MessageHolder(rootView, onItemClickListener);
}
@Override
public void onBindViewHolder(MessageHolder holder, int position) {
holder.setData(context, dataList.get(position));
}
@Override
public int getItemCount() {
return dataList.size();
}
public void addAll(List<Message> dataList) {
this.dataList.addAll(dataList);
notifyDataSetChanged();
}
public void clear() {
this.dataList.clear();
notifyDataSetChanged();
}
public List<Message> getAll() {
return this.dataList;
}
OnMsgItemClickListener onItemClickListener;
public void setOnItemClickListener(OnMsgItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public interface OnMsgItemClickListener {
void onItemClick(View view, Message message);
}
}
class MessageHolder extends RecyclerView.ViewHolder {
private MessageAdapter.OnMsgItemClickListener onItemClickListener;
private TextView tv_title;
private TextView tv_content;
private TextView tv_time;
private LinearLayout ll;
MessageHolder(View itemView, MessageAdapter.OnMsgItemClickListener onItemClickListener) {
super(itemView);
this.onItemClickListener = onItemClickListener;
tv_title = (TextView) itemView.findViewById(R.id.tv_title);
tv_time = (TextView) itemView.findViewById(R.id.tv_time);
tv_content = (TextView) itemView.findViewById(R.id.tv_content);
ll = (LinearLayout) itemView.findViewById(R.id.ll);
}
public void setData(final Context context, final Message message) {
if (message == null) {
return;
}
tv_title.setText(message.msgTitle);
tv_time.setText(DateTimeUtils.parseDatetime(message.createTime));
tv_content.setText(message.msgContent);
ll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick(v, message);
}
}
});
}
}