android studio中使用recyclerview小白篇

枕上从妨一夜睡,灯前读尽十年诗。这篇文章主要讲述android studio中使用recyclerview小白篇相关的知识,希望能为你提供帮助。
继续接着昨天的来,昨天终于弄好了一个例子,但是那个没有点击事件, 需要自己添加,参照别人的例子,弄了个比较简单的,主要是改动myRecycleradatper.java中的部分.
增加如下的接口:

//增加一个静态的接口. private OnItemClickListener listener; public static interface OnItemClickListener { void onItemClick(View view , int position); } public void setOnItemClickListener(OnItemClickListener listener) { this.listener = listener; }

【android studio中使用recyclerview小白篇】
在onBindViewHolder中增加如下的代码
if (listener != null) { holder.v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onItemClick(v,position); } }); }


这就好了,是目前能找到的比较简洁的方法了.
在主界面中直接使用就可以了.如下:
recycleAdapter.setOnItemClickListener(new myRecycleradatper.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Log.e("constr"," " + position); } });


观看点击后log.e的记录值.
 
自定义的数据适配器全部代码如下,供参照,虽然不好,但是能用,我也不知啥意思,以后慢慢理解吧:
public class myRecycleradatper extends RecyclerView.Adapter< myRecycleradatper.MyViewHolder> { private List< filelist> mDatas; private Context mContext; private LayoutInflater inflater; //增加一个静态的接口. private OnItemClickListener listener; public static interface OnItemClickListener { void onItemClick(View view , int position); } public void setOnItemClickListener(OnItemClickListener listener) { this.listener = listener; }public myRecycleradatper(Context context, List< filelist> datas){ this. mContext=context; this. mDatas=datas; inflater=LayoutInflater. from(mContext); }@Override public int getItemCount() { return mDatas.size(); } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {View view = inflater.inflate(R.layout.item_view,parent, false); MyViewHolder holder= new MyViewHolder(view); return holder; }@Override public void onBindViewHolder(MyViewHolder holder, final int position) { filelist da=mDatas.get(position); if(position%2==0){ //holder.tv.setBackgroundColor(Color.BLUE); holder.v.setBackgroundColor(Color.GRAY); } if (listener != null) { holder.v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onItemClick(v,position); } }); } holder.tv.setText(da.getName()); holder.msg.setText(da.getZt()); }class MyViewHolder extends RecyclerView.ViewHolder{ TextView tv; TextView msg; View v; public MyViewHolder(View view) { super(view); tv=(TextView) view.findViewById(R.id.txt_xs); msg=(TextView)view.findViewById(R.id.txt_msg); v=view; }} }


 

    推荐阅读