效果如下:
public class MainActivity extends AppCompatActivity {
//第一步:定义对象
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//第二步:绑定控件
listView = (ListView) findViewById(R.id.list_view);
//第三步:创建一个列表 准备数据(数据源)
List<Fruit> fruitlist = new ArrayList<>();
for (int i = 0; i <5 ; i++) {//列表整体重复次数
Fruit pineapple=new Fruit(R.drawable.pic1,"菠萝","¥16.9 元/KG");
fruitlist.add(pineapple);
Fruit mango = new Fruit(R.drawable.pic2, "芒果","¥29.9 元/kg");
fruitlist.add(mango);
Fruit pomegranate = new Fruit(R.drawable.pic3, "石榴","¥15元/kg");
fruitlist.add(pomegranate);
Fruit grape = new Fruit(R.drawable.pic4, "葡萄","¥19.9 元/kg");
fruitlist.add(grape);
}
//第四步:设计每一个列表项的子布局 即fruit_item.xml文件
//第五步:定义适配器 控件-桥梁-数据源
FruitAdapter adapter=new FruitAdapter(MainActivity.this,R.layout.fruit_item,
fruitlist);
listView.setAdapter(adapter);//将适配器加载到控件中
//列表点击事件
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent ,View view, int position,long id) {
Fruit fruit = fruitlist.get(position);
Toast.makeText(MainActivity.this,fruit.getName(),Toast.LENGTH_LONG).show();
}//通过position判断用户点击的是哪一个子项
});
}
}
public class Fruit {
private int imageID;
private String name;
private String price;
public int getImageID() {
return imageID;
}
public String getName() {
return name;
}
public String getPrice() {
return price;
}
public Fruit(int imageID, String name, String price) {
this.imageID = imageID;
this.name = name;
this.price = price;
}
}
public class FruitAdapter extends ArrayAdapter<Fruit> {
public FruitAdapter(@NonNull Context context, int resource, @NonNull List<Fruit> objects) {
super(context, resource, objects);
}
//每个子项被滚动到屏幕内的时候会被调用
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
Fruit fruit=getItem(position);//得到当前项的 Fruit 实例
//为每一个子项加载设定的布局
View view=LayoutInflater.from(getContext()).inflate(R.layout.fruit_item,parent,false);
//分别获取 image view 和 textview 的实例
ImageView fruitimage =view.findViewById(R.id.fruit_image);
TextView fruitname =view.findViewById(R.id.fruit_name);
TextView fruitprice =view.findViewById(R.id.fruit_price);
// 设置要显示的图片和文字
fruitimage.setImageResource(fruit.getImageID());
fruitname.setText(fruit.getName());
fruitprice.setT