package com.example.health.foodlist; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.example.health.Bean.FoodBean; import com.example.health.R; import java.util.List; public class ListAdapter extends BaseAdapter { Context context; ListmDatas; public ListAdapter(Context context, List mDatas) { this.context = context; this.mDatas = mDatas; } //决定了ListView展示列表的行数 @Override public int getCount() { return mDatas.size(); } //返回指定位置对应的数据 @Override public Object getItem(int position) { return mDatas.get(position); } //返回指定位置对应的id @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.foodlist,null);//将布局转换成view对象的方法 holder = new ViewHolder(convertView); convertView.setTag(holder); }else{ holder = (ViewHolder) convertView.getTag(); } //加载控件显示的内容 //获取集合指定位置的数据 FoodBean foodBean = mDatas.get(position); holder.iv.setImageResource(foodBean.getPicID()); holder.fname.setText(foodBean.getFoodName()); holder.fcalo.setText(foodBean.getFoodCalorie());//这三步用于显示内容 return convertView; } class ViewHolder{ ImageView iv; TextView fname,fcalo; public ViewHolder(View view){ iv = view.findViewById(R.id.item_foodpic); fname = view.findViewById(R.id.item_foodtitle); fcalo = view.findViewById(R.id.item_calorie); } } }