一、Adapter
class FruitAdapter: ArrayAdapter{
constructor(context: Context?, textViewResourceId: Int, objects: List?) :super(context, textViewResourceId, objects)
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var fruit:Fruit = getItem(position)
var view:View
var viewHolder:ViewHolder
if (convertView ==null) {
view = LayoutInflater.from(context).inflate(R.layout.fruit_item,parent,false)
viewHolder = ViewHolder()
viewHolder.fruitImage = view.findViewById(R.id.fruit_image)
viewHolder.fruitName = view.findViewById(R.id.fruit_name)
view.setTag(viewHolder)
}else {
view = convertViewas View
viewHolder = view.getTag()as ViewHolder;
}
viewHolder.fruitImage!!.setImageResource(fruit.imageId)
viewHolder.fruitName!!.setText(fruit.name)
return view!!
}
class ViewHolder {
var fruitImage:ImageView? =null
var fruitName:TextView? =null
}
}
listView = (ListView)findViewById(R.id.list_view);
FruitAdapter adapter =new FruitAdapter(MainActivity.this,R.layout.fruit_item,fruitLists);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView adapterView, View view, int i, long l) {
Fruit fruit =fruitLists.get(i);
Toast.makeText(MainActivity.this,fruit.getName(),Toast.LENGTH_SHORT).show();
}
});