RecyclerView 实例

RecyclerView 实例

完整代码:[ https://github.com/zjbpku/recyclerviewdemo ] (使用AndroidStudio)

关于在使用RecyclerView时如何实现Item的点击事件问题,这里用一个简单方法实现:

ViewHolder:

/**
 * Created by jabin on 6/1/15.
 */
public class RcvViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    public CardView cv;
    public TextView tvTitle;
    public TextView tvContent;
    public ImageView ivIcon;
    ViewHolderOnClick mViewHolderOnClick;

    RcvViewHolder(final View viewitem) {
        super(viewitem);
        cv = (CardView) viewitem.findViewById(R.id.cv);
        tvTitle = (TextView) viewitem.findViewById(R.id.tvTitle);
        tvContent = (TextView) viewitem.findViewById(R.id.tvContent);
        ivIcon = (ImageView) viewitem.findViewById(R.id.ivIcon);
        cv.setOnClickListener(this);
    }


    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        if (mViewHolderOnClick != null) {
            mViewHolderOnClick.onItemClicked(v, getLayoutPosition());
        }
    }

    public void setOnItemClickListener(ViewHolderOnClick viewHolderOnClick) {
        this.mViewHolderOnClick = viewHolderOnClick;
    }
    //定义接口
    public interface ViewHolderOnClick {
         void onItemClicked(View view, int position);
    }

}

Adapter:

     @Override
    public RcvViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_hold, parent, false);
        RcvViewHolder rcvViewHolder = new RcvViewHolder(view);
        rcvViewHolder.setOnItemClickListener(new RcvViewHolder.ViewHolderOnClick() {
            @Override
            public void onItemClicked(View view, int position) {
                Toast.makeText(view.getContext(), "positon: " + position, Toast.LENGTH_SHORT).show();
            }
        });
        return rcvViewHolder;
    }

你可能感兴趣的:(android)