RecyclerView使用方法总结

RecyclerView( android.support.v7.widget.RecyclerView)是安卓新推出的一个滑动组件,感觉是用来替代ListView实现更多的效果,使用时和ListView相比也是不同,这里记录下用法:

1、线性布局(LinearLayoutManager):

 首先是确定布局类型,使用LinearLayoutManager来定义:

LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);

下来是设置Adapter,和ListView的不同,RecyclerView必须自定义一个RecyclerView.Adapter来实现:

//recylerview的数据适配器
class mRecyclerViewAdapter extends RecyclerView.Adapter<mRecyclerViewAdapter.ViewHolder>{

    
    // 自定义内部的ViewHolder
    public static class ViewHolder extends RecyclerView.ViewHolder {
        
        public TextView mTextView;

        public ViewHolder(View v) {
            super(v);
         mTextView = (TextView) v.findViewById(R.id.showtext); 
        }
    }

    private ArrayList<String> mArryList;

    private Context mContext;
 
    public mRecyclerViewAdapter(Context context,ArrayList<String> list){
        mContext = context;
        mArryList = list;
    }

    @Override
    public int getItemCount() {
        // TODO Auto-generated method stub
        return mArryList.size();
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int pos) {
         holder.mTextView.setText(mArryList.get(pos));
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup arg0, int arg1) {
        View v = LayoutInflater.from(mContext).inflate(
                R.layout.recyleview_item_layout, null);
        final ViewHolder vh = new ViewHolder(v);
        return vh;
    }
}

 点击事件的实现:将内部点击事件通过接口传递到外部:

 定义接口:

interface OnRecyclerViewItemClickListener {
    void onRecyclerClick(View view, int pos);
}

 adapter内部定义接口实例:

    private OnRecyclerViewItemClickListener mOnItemClickListener = null;
    public void setmOnItemClickListener(
            OnRecyclerViewItemClickListener mOnItemClickListener) {
        this.mOnItemClickListener = mOnItemClickListener;
    }

adapter内部View事件绑定:

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int arg1) {
       //注意这里要传入parent元素,否则V的宽度无法math_parent
View v
= LayoutInflater.from(mContext).inflate( R.layout.recyleview_item_layout, parent ,false);
final ViewHolder vh = new ViewHolder(v); v.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mOnItemClickListener != null) { mOnItemClickListener.onRecyclerClick(v, vh.getPosition()); } } }); return vh; } }

 外部调用:

final mRecyclerViewAdapter mrecyleadapter = new mRecyclerViewAdapter(testList, this);
        mRecyclerViewAdapter 
                .setOnItemClickListener(new OnRecyclerViewItemClickListener() {
                    @Override
                    public void onRecyclerClick(View view, int pos) {
                          dowhat...
                    }
                });

 待续...

你可能感兴趣的:(RecyclerView使用方法总结)