RecyclerView之基本使用

2019-12-16  本文已影响0人  钦_79f7

简介

RecyclerView是support-v7包中的新组件,是一个强大的滑动组件,与经典的ListView相比,同样拥有item回收复用的功能,但是直接把viewholder的实现封装起来,用户只要实现自己的viewholder就可以了,该组件会自动帮你回收复用每一个item。

它不但变得更精简,也变得更加容易使用,而且更容易组合设计出自己需要的滑动布局。

compile 'com.android.support:recyclerview-v7:25.3.1'

基本使用

private void initRecyclerView() {
        //设置LayoutManager,这里设置的是垂直线性布局管理
        recylerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        //设置item的装饰(例如divider间隔or其他装饰)
        recylerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
            }
        });
        //设置item动画
        recylerView.setItemAnimator();
        //设置适配器
        recylerView.setAdapter(new MyAdapter(dataList, this, R.layout.item_layout));
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView textView;

        public MyViewHolder(View itemView) {
            super(itemView);
            textView = ((TextView) itemView.findViewById(R.id.text_view));
        }
    }

    class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

        List<String> datas;
        LayoutInflater mInflater;
        Context ctx;
        @LayoutRes
        int layoutId;

        public MyAdapter(List<String> datas, Context ctx, int layoutId) {
            this.datas = datas;
            this.ctx = ctx;
            this.layoutId = layoutId;
        }

        /**
         * @param parent   The ViewGroup into which the new View will be added after it is bound to
         *                 an adapter position.
         * @param viewType The view type of the new View.
         * @return 为每个item创建ViewHolder
         */
        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = mInflater.inflate(layoutId, parent, false);
            return new MyViewHolder(itemView);
        }

        /**
         * 为item绑定数据
         *
         * @param holder   The ViewHolder which should be updated to represent the contents of the
         *                 item at the given position in the data set.
         * @param position The position of the item within the adapter's data set.
         */
        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            holder.textView.setText(datas.get(position));
        }

        /**
         * @return item总数
         */
        @Override
        public int getItemCount() {
            return datas.size();
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读