目录:
1 单一类型数据展示
2 多种类型数据展示
3 添加setOnItemClickListener监听
4 添加Header、Footer
5 封装成通用的方式
1 单一数据展示:
Google一下,一堆堆的,就不再制造垃圾了。
2 多种类型数据展示:
由于最后需要封装成通用的方式,这一步还是要写的。
1 定义两种ViewHolder:
// 普通ViewHolder
public static class ViewHolderNormal
extends RecyclerView.ViewHolder {
public TextView mTextView;
public View layout;
public ViewHolderNormal(View v) {
super(v);
layout = v;
mTextView = (TextView) v.findViewById(R.id.tv);
}
}
//带有RadioButton的ViewHolder
public static class ViewHolderRadioButton extends RecyclerView.ViewHolder {
public TextView mTextView;
public RadioButton radioButton;
public View layout;
public ViewHolderRadioButton(View itemView) {
super(itemView);
layout = itemView;
mTextView = (TextView) itemView.findViewById(R.id.tv);
radioButton = (RadioButton) itemView.findViewById(R.id.radio);
}
}
2 重写:getItemViewType
@Override
public int getItemViewType(int position) {
int type = 1;
if (position % 2 == 0) {
type = 2;
}
return type;
}
3 重写:onCreateViewHolder:
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder holder = null;
if (viewType == 1) {
View view = LayoutInflater.from(context).inflate(R.layout.main_shop_item, parent, false);
holder = new ViewHolderNormal(view);
} else if (viewType == 2) {
View view = LayoutInflater.from(context).inflate(R.layout.main_shop_item_2, parent, false);
holder = new ViewHolderRadioButton(view);
}
return holder;
}
4 重写onBindViewHolder:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof ViewHolderNormal){
ViewHolderNormal holderNormal = (ViewHolderNormal)holder;
WebInfoBean bean = list.get(position);
StringUtil.SetTextView(bean.name, holderNormal.mTextView);
holderNormal.layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onItemClickListener.onItemClick(v, position);
}
});
}else if (holder instanceof ViewHolderRadioButton){
ViewHolderRadioButton holderRadioButton = (ViewHolderRadioButton)holder;
WebInfoBean bean = list.get(position);
StringUtil.SetTextView(bean.name,holderRadioButton.mTextView);
holderRadioButton.radioButton.setChecked(true);
}
}
3 添加setOnItemClickListener监听:
//定义监听回调接口
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
//对外提供设置接口方法
public void setOnItemClickListener(OnItemClickListener listener) {
this.onItemClickListener = listener;
}
//在onBindViewHolder中添加监听,参考上面onBindViewHolder中代码
//在Activity初始化中调用:
adapter.setOnItemClickListener(new ShopAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
LogUtil.d("positon:" + position);
}
});
4 添加Header:
http://www.tuicool.com/articles/qMnAfen