简单的RecyclerView例子

2020-04-17  本文已影响0人  大白520

1、xml添加标签RecyclerView

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>

activity

        RecyclerView recyclerView = findViewById(R.id.recyclerview);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);

        //设置为垂直布局,这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);

        //设置Adapter
        recyclerView.setAdapter(new RecyclerAdapter());

        //设置分隔线
        //recyclerView.addItemDecoration( new DividerGridItemDecoration(this));

        //设置增加或删除条目的动画
        //recyclerView.setItemAnimator( new DefaultItemAnimator());

RecyclerAdapter

    class RecyclerAdapter extends RecyclerView.Adapter<ItemViewHolder> {

        @Override
        public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.rec_item, parent, false);
            return new ItemViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ItemViewHolder itemViewHolder, int i) {
            itemViewHolder.title.setText(""+i);
        }

        @Override
        public int getItemCount() {
            return 20;
        }
    }

    class ItemViewHolder extends RecyclerView.ViewHolder {

        public TextView title;

        private ItemViewHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.title);
        }
    }
上一篇下一篇

猜你喜欢

热点阅读