RecyclerVier简介

RecyclerViewAndroid一个更强大的控件,其不仅可以实现和ListView同样的效果,还有优化了ListView中的各种不足。其可以实现数据纵向滚动,也可以实现横向滚动(ListView做不到横向滚动)。

添加RecyclerView 依赖库

    implementation 'androidx.recyclerview:recyclerview:1.0.0'

RecyclerView的配置

布局配置

        //线性布局(Context context, @RecyclerView.Orientation int orientation,
            boolean reverseLayout)
        // 参数:上下环境,水平方向,布局是否翻转
        mLinearLayoutManager= new LinearLayoutManager(mContext, RecyclerView.HORIZONTAL,false);
        //瀑布流(int spanCount, int orientation)
        //参数:一行4列和垂直方向
        mStaggeredGridLayoutManager= new StaggeredGridLayoutManager(4, RecyclerView.VERTICAL);
        //网格布局(Context context, int spanCount)
        //参数:上下环境和一行4列
        mGridLayoutManager= new GridLayoutManager(this, 4); //一行4列

        //需要设置LayoutManager之后才能显示
        mRecyclerView.setLayoutManager(mGridLayoutManager);
        mRecyclerView.setAdapter(fruitAdapter);

Adapter定义

public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {

    private Context mContext;
    private String[] fruitName;

    public FruitAdapter(Context context, String[] fruits) {
        this.mContext = context;
        this.fruitName = fruits;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_fruit, null);
        ViewHolder viewHolder = new ViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.tvName.setText(fruitName[position]);
    }

    @Override
    public int getItemCount() {
        if (null != fruitName) {
            return fruitName.length;
        }
        return 0;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView tvName;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            tvName = itemView.findViewById(R.id.fruit_name);
        }
    }
}

相关文章

暂无评论

none
暂无评论...