自定义RecyclerView的GridLayoutManger的实现效果

adapter = new CommodityRecommendationAdapter(this, datas);
rv_commodity_recommendation.setLayoutManager(new GridLayoutManager(this,2));
rv_commodity_recommendation.setAdapter(adapter);
adapter.notifyDataSetChanged();

适配器:

public class CommodityRecommendationAdapter extends RecyclerView.Adapter<CommodityRecommendationAdapter.CommodityViewHolder> {
    private Context context;
    private List<CommodityRecommendation> datas = new ArrayList<>();

    public CommodityRecommendationAdapter(Context context, List<CommodityRecommendation> datas) {
        super();
        this.context = context;
        this.datas = datas;
    }
    @Override
    public CommodityViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View  view = LayoutInflater.from(context).inflate(R.layout.commodityrecommendation_item,null);
        CommodityViewHolder thirdViewHolder = new CommodityViewHolder(view);
        return thirdViewHolder;
    }

    @Override
    public void onBindViewHolder(CommodityViewHolder holder, int position) {
        holder.tv_productname.setText(datas.get(position).getProductname());
        holder.tv_price.setText("¥"+datas.get(position).getPrice());
        holder.tv_commodity_price.setText("¥"+datas.get(position).getCommodity_price());
    }



    @Override
    public int getItemCount() {
        return datas.size();
    }
    class CommodityViewHolder extends RecyclerView.ViewHolder{
       TextView tv_productname;
       TextView tv_price;
       TextView tv_commodity_price;

        public CommodityViewHolder(View itemView) {
            super(itemView);
            tv_productname = (TextView) itemView.findViewById(R.id.tv_productname);
            tv_price = (TextView) itemView.findViewById(R.id.tv_price);
            tv_commodity_price = (TextView) itemView.findViewById(R.id.tv_commodity_price);
        }
    }
}

实现的效果图:

猜你喜欢

转载自blog.csdn.net/qq_35572449/article/details/81204204