android关于RecyclerView的使用

来源:转载

只说要点。

1、自定义的ViewHolder需要继承RecyclerView-V7包里的ViewHolder ,实现构造方法。

2、自定义的adapter需要继承RecyclerView-V7包里的Adapter<T>,也就是RecyclerView-V7包里的Adapter<自定义的ViewHolder>。需要实现:getItemCount方法、onCreateViewHolder方法(返回自定义的ViewHolder)、onBindViewHolder方法

3、定义LayoutManager ,LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);

4、可以设置LayoutManager 的方向,linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

5、把LayoutManager 给RecyclerView,mRecyclerView.setLayoutManager(linearLayoutManager);

6、最后是绑定适配器,mRecyclerView.setAdapter(adapter);



下面是适配器的一个example:


public class GalleryAdapter extends Adapter<GalleryAdapter.MViewHolder> {

/**
* ItemClick的回调接口
*/
public interface OnItemClickLitener {
void onItemClick(View view, int position);
}

private OnItemClickLitener mOnItemClickLitener;

public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) {
this.mOnItemClickLitener = mOnItemClickLitener;
}

/***************************************************/
private LayoutInflater mInflater;
private List<Integer> mDatas;

public GalleryAdapter(Context context, List<Integer> datats) {
mInflater = LayoutInflater.from(context);
mDatas = datats;
}

public static class MViewHolder extends ViewHolder {
public MViewHolder(View inflateView) {
super(inflateView);
mImg = (ImageView) inflateView
.findViewById(R.id.id_index_gallery_item_image);
}

ImageView mImg;
TextView mTxt;
}

@Override
public int getItemCount() {
return mDatas.size();
}

@Override
public MViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = mInflater.inflate(R.layout.activity_index_gallery_item,
viewGroup, false);
MViewHolder viewHolder = new MViewHolder(view);

return viewHolder;
}

@Override
public void onBindViewHolder(final MViewHolder viewHolder, final int i) {
viewHolder.mImg.setImageResource(mDatas.get(i));

// 如果设置了回调,则设置点击事件
if (mOnItemClickLitener != null) {
viewHolder.itemView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mOnItemClickLitener.onItemClick(viewHolder.itemView, i);
}
});

}

}

}



分享给朋友:
您可能感兴趣的文章:
随机阅读: