RecyclerView

    //列表添加分割线(画分隔线)
rv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDrawOver(Canvas c, RecyclerView parent) {
                Paint p =new Paint();
                p.setColor(Color.BLUE);
                for (int i=0;i<parent.getChildCount();i++){
                   View v = parent.getChildAt(i);
                    //画水平位置的分隔线
                    c.drawLine(v.getLeft(),v.getBottom(),v.getRight(),v.getBottom(),p);
                    //画竖直位置的分隔线(GridView)
                    c.drawLine(v.getRight(),v.getTop(),v.getRight(),v.getBottom(),p);
                }
            }

        });


自定义RecyclerView的适配及点击监听事件、数据的添加及删除:


package com.blhcn.recyclerviewdemo;


import java.util.List;


import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;


public class MyRecyAdapter extends RecyclerView.Adapter<MyRecyAdapter.MyViewHolder> {


private List<String> list;
private Context mContext;
private OnItemClickListener mListener;

public MyRecyAdapter(List<String> list, Context mContext) {
super();
this.list = list;
this.mContext = mContext;
if(mContext instanceof OnItemClickListener){
mListener=(OnItemClickListener) mContext;
}


}

class MyViewHolder extends RecyclerView.ViewHolder implements OnClickListener{
private TextView txtv;
private OnItemClickListener listener;
public MyViewHolder(View itemView,
OnItemClickListener listener) {
super(itemView);

txtv=(TextView)itemView.findViewById(R.id.txtv);
this.listener = listener;
itemView.setOnClickListener(this);

}


@Override
public void onClick(View v) {
if(listener!=null){
listener.onItemClick(getPosition(), list.get(getPosition()));
}
}

}

/
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.item_main, null);
return new MyViewHolder(v,mListener);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.txtv.setText(list.get(position));
}

@Override
public int getItemCount() {
return list == null ? 0 : list.size();
}

//定义接口监听 public interface OnItemClickListener { void onItemClick(int position, String data); } public void setListener(OnItemClickListener mListener) { this.mListener = mListener; } /**  * 添加数据  * @param position  * @param data  */ public void add(int position, String data) { list.add(position, data); notifyItemInserted(position); } /**  * 删除数据  * @param position  */ public void remove(int position) { list.remove(position); notifyItemInserted(position); } }

相关文章
相关标签/搜索