Android 利用RecyclerView 的SnapHelper 实现滚轮效果

在support V4的最新包中,谷歌加入了一个叫做SnapHelper的辅助类。这个类的作用是可以让RecyclerView实现一些类似ViewPager的效果。我大致试了下,可以利用这个类实现滚轮选择效果。如果所示:

Android 利用RecyclerView 的SnapHelper 实现滚轮效果_第1张图片

核心代码如下:

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        LinearSnapHelper linearSnapHelper = new LinearSnapHelper();
        linearSnapHelper.attachToRecyclerView(mRecyclerView);
        mAdapter = new RecyclerViewAdapter(this);
        mRecyclerView.setAdapter(mAdapter);
其中Adapter代码如下:

public class RecyclerViewAdapter extends RecyclerView.Adapter {
    private List mDataList = new ArrayList<>();
    private Context mContext;

    public RecyclerViewAdapter(Context context) {
        mContext = context;

        for (int i = 0; i < 200; i++) {
            mDataList.add("" + i);
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View headerView = View.inflate(mContext, R.layout.item, null);
        MyViewHolder headerHolder = new MyViewHolder(headerView);
        return headerHolder;

    }

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

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


    public static class MyViewHolder extends RecyclerView.ViewHolder {
        TextView textView;

        public MyViewHolder(View view) {
            super(view);
            textView = (TextView) view.findViewById(R.id.id_info);
        }
    }
}
item 的布局文件代码如下:



    

    

    


补记:

系统还帮我们实现了一个PagerSnapHelper,可以用RecyclerView实现跟ViewPager一模一样的效果:

PagerSnapHelper linearSnapHelper = new PagerSnapHelper();
具体的item 的XML 代码如下:



    





你可能感兴趣的:(Android 利用RecyclerView 的SnapHelper 实现滚轮效果)