适配器.:就是把一些数据在View上显示。可以看作是界面数据绑定的一种理解。它所操纵的数据一般都是一些比较复杂的数据,如数组,链表, 数据库,集合等。
eg:
String[] sex = new String(){"男",“女”}//数据源
ArrayAdapter adapter;//数组适配器,用的是泛型
adapter=new ArrayAdapter(this,Android.R.Layout.Simple_List_Item_1,sex);
this.setAdapter(adapter);二:List作为数据源,填充的是SimpleAdapter
eg:
ListView list = (ListView)findViewById(R.id.MyListView);
//生成动态数组,并且转载数据
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
for(int i=0;i<30;i++)
{
HashMapmap = new HashMap();map.put("ItemTitle","This is Title.....");
map.put("ItemText","This is text.....");
mylist.add(map);
}
//生成适配器,数组
SimpleAdapter mSchedule = new SimpleAdapter(this,mylist,R.layout.my_listitem, new String[]{"ItemTitle", "ItemText"}, new int[] {R.id.ItemTitle,R.id.ItemText});
//添加并且显示
list.setAdapter(mSchedule);
}三:定义自己的适配器
为什么要定义自己的适配器呢,原因就在于,当我们想用一些其它的展现方式,或者是我们需要的,呈现方式,这是就得DIY了。
首先我们定义一个类让它继承自BaseAdapter,再让它实现一里面所说的那几个方法。那么这个自定义适配器就算好了。
里面的一些方法我在上面都介绍过了,在这就不在赘述了。
public class ImageAdapter extendsBaseAdapter {
private Context mcontext;
private int imageIds;
//构造函数里面有两个参数,一个是数据的来源,另一个是上下文。
public ImageAdapter(Integer[] imgIds,Context c){mcontext=c;
imageIds=imgIds;
}
publicint getCount() {
// TODO Auto-generated method stub
return imageIds.length;
}
// TODO Auto-generated method stub
return null;
}
publiclong getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
//主要是在这里,可以自定义布局,重点
publicView getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageview = newImageView(mcontext);
imageview.setImageResource(imageIds[position]);
imageview.setLayoutParams(newGallery.LayoutParams(120,120));
imageview.setScaleType(ImageView.ScaleType.FIT_CENTER);
return imageview;
}
}
现在应该知道为什么用适配器和如何用了吧!大家技术更进一步。。