Android RecyclerView网格布局的学习

最近用到 RecyclerView的网格布局,简单学习了一个Demo,效果如下

Android RecyclerView网格布局的学习_第1张图片

下面是代码

public class GridViewDemo extends AppCompatActivity {
    private RecyclerView recyclerView;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gridview_demo);
        recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        
        //这里的第二个参数6代表的是网格的列数
        recyclerView.setLayoutManager(new GridLayoutManager(this, 6));
        recyclerView.setAdapter(new GridAdapter());
    }
 
    class GridAdapter extends RecyclerView.Adapter {
        @Override
        public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_horizontal_recyclerviedw, parent, false);
            Holder holder = new Holder(view);
            return holder;
        }
 
        @Override
        public void onBindViewHolder(Holder holder, int position) {
            holder.textView.setText("第" + position + "元素");
        }
 
        @Override
        public int getItemCount() {
            return 20;
        }
 
        class Holder extends RecyclerView.ViewHolder {
            private TextView textView;
            public Holder(View itemView) {
                super(itemView);
                textView = (TextView)itemView.findViewById(R.id.textView);
            }
        }
    }
}

整体比较简单好用

你可能感兴趣的:(Android)