粗略总结第一行代码
说道用ListView,就是一个下拉列表。
ListView有个好基友叫Adapter,每当ListView要呈现数据了,Adapter就会出来帮他获取数据源。
基本常用的Adapter有:
ArrayAdapter:展示一行;
SimpleAdapter:有最好的扩充性,可以自定义各种各样的布局,除了文本外,还可以放ImageView(图片)、Button(按钮)、CheckBox(复选框)等等;
SimpleCursorAdapter:可以认为是SimpleAdapter对数据库的简单结合,可以方便地把数据库的内容以列表的形式展示出来。
一般我们都要自定义一个Adapter它通常继承于BaseAdapter
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFruits();
FruitAdapter fruitAdapter=new FruitAdapter(MainActivity.this,
R.layout.fruit_item,fruitList);
ListView listView=(ListView)findViewById(R.id.list_view);
listView.setAdapter(fruitAdapter);
}
public class FruitAdapter extends ArrayAdapter<Fruit> {
private int resourceId;
public FruitAdapter(Context context, int textViewResourceId, List<Fruit> objects){
super(context,textViewResourceId,objects);
resourceId=textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Fruit fruit=getItem(position);
View view;
ViewHolder viewHolder;
if(convertView==null){
view=LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
viewHolder=new ViewHolder();
viewHolder.fruitImage=(ImageView)view.findViewById(R.id.fruit_image);
viewHolder.fruitName=(TextView) view.findViewById(R.id.fruit_name);
view.setTag(viewHolder);
}else{
view=convertView;
viewHolder=(ViewHolder)view.getTag();
}
/* ImageView fruitImage=(ImageView)view.findViewById(R.id.fruit_image);
TextView fruitName=(TextView)view.findViewById(R.id.fruit_name);
fruitImage.setImageResource(fruit.getImageId());
fruitName.setText(fruit.getName());*/
viewHolder.fruitImage.setImageResource(fruit.getImageId());
viewHolder.fruitName.setText(fruit.getName());
return view;
}
class ViewHolder{
ImageView fruitImage;
TextView fruitName;
}
}