RecyclerView大家都不陌生了,都知道他的列表数据操作是使用实现RecyclerView.Adapter使用里面的方法操作做的。接下来我给大家实现下基本的方法实现。
比方说现在要实现一个商品列表的adapter,就要定义一个商品的类 Goods
public class Goods{
private String name;
private int price;
public Goods(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
定义GoodViewHolder类
import android.view.View;
import android.widget.TextView;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class GoodsViewHolder extends RecyclerView.ViewHolder {
private TextView name;
private TextView price;
public GoodsViewHolder(@NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
price = itemView.findViewById(R.id.price);
}
}
定义GoodsAdapter类
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class GoodsAdapter extends RecyclerView.Adapter<GoodsViewHolder> {
List<Goods> goodsList;
Context context;
public GoodsAdapter(Context context) {
this.context = context;
goodsList = new ArrayList<>();
}
@NonNull
@Override
public GoodsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.goods_layout, null);
return new GoodsViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull GoodsViewHolder holder, int position) {
final Goods goods = goodsList.get(position);
holder.name.setText(goods.getName());
holder.price.setText(goods.getPrice());
}
@Override
public int getItemCount() {
return goodsList.size();
}
//初始化商品列表
public void setDatas(List<Goods> list) {
if (list != null && list.size() > 0) {
if (this.goodsList.size() > 0)
this.goodsList.clear();
this.goodsList.addAll(list);
notifyDataSetChanged();
}
}
//在指定位置插入多条数据
public void insertDatas(List<Goods> list, int pos) {
if (list != null && list.size() > 0) {
this.goodsList.addAll(list);
notifyItemRangeInserted(pos, list.size());
}
}
//在指定位置插入一条数据
public void insertItem(Goods goods, int pos) {
this.goodsList.add(pos, goods);
notifyItemInserted(pos);
}
//删除单条数据
public void deleteItem(Goods goods) {
int pos = this.goodsList.indexOf(goods);
if (pos >= 0) {
this.goodsList.remove(pos);
notifyItemRemoved(pos);
}
}
}
这里要注意的是delete按钮里面的pos不能是positon,不然删除到最后会出现数组索引异常,因为删除的时候对应的position和在goodslist里面的索引不一致