class
参考书籍《第一行代码》
Fruit适配器
public class FruitAdapter extends ArrayAdapter {
private int resourceId;
public FruitAdapter(@NonNull Context context, int textViewResourceId, List<Fruit> objects) {
super(context,textViewResourceId,objects);
this.resourceId = textViewResourceId;
}
class ViewHolder{
TextView fruitText;
ImageView fruitImage;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
Fruit fruit = (Fruit)getItem(position);
View view;
ViewHolder viewHolder;
/*
convertView可以将之前的布局进行缓存 因此只要第一次存储 之后直接用即可
*/
if(convertView == null ){
/*
如果是空的 那么说明convertView还没有加载
加载动态布局
*/
view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
viewHolder = new ViewHolder();
viewHolder.fruitImage = view.findViewById(R.id.fruit_image);
viewHolder.fruitText = view.findViewById(R.id.fruit_text);
view.setTag(viewHolder); //将viewHolder存进view中
}
else{
view = convertView; //从这里取出
viewHolder = (ViewHolder) view.getTag();
}
//设置显示的数据
viewHolder.fruitText.setText(