10.安卓(listview的使用)

item.xml


<TextView
android:id="@+id/tv_name"
android:layout_width="100dp"
android:layout_height="wrap_content"
/>

<TextView
android:id="@+id/tv_age"
android:layout_width="100dp"
android:layout_height="wrap_content"
/>

<TextView
android:id="@+id/tv_phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

 

 

 

 

方法1.  hashmap相对应,不过扩展不是怎么行

view = (ListView) this.findViewById(R.id.listview);

 

private void show()
{
DataBase d = new DataBase(this);//创建一个数据库
List<Student> list = d.GetAll_Fy(10, 20);//获得一些学生
List<HashMap<String, Object>> lMap = new ArrayList<HashMap<String,Object>>();
for (Student student : list) {
HashMap<String, Object> hash = new HashMap<String, Object>();
hash.put("name", student.getName());
hash.put("age", student.getAge());
hash.put("phone", student.getPhone());
lMap.add(hash);
}
SimpleAdapter sa = new SimpleAdapter(this, lMap, R.layout.item, new String[]{"name","age","phone"}, new int[]{R.id.tv_name,R.id.tv_age,R.id.tv_phone});

                                        这个是hash的key                           这个是item.xml里面的id,
view.setAdapter(sa);  添加适配器
}

 

方法2., 直接用Cursor 光标进行适配

 

//分页查询,返回Cursor
public Cursor GetCursor_Fy(int offset, int maxResult)
{
SQLiteDatabase sd = this.getReadableDatabase();
Cursor cur = sd.rawQuery("select studentid as _id,* from student limit ?,?", new String[]{String.valueOf(offset),String.valueOf(maxResult)});
return cur;
}

 

private void show2() {
DataBase d = new DataBase(this);
SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.item, d.GetCursor_Fy(10, 20), new String[]{"name","age","phone"}, new int[]{R.id.tv_name,R.id.tv_age,R.id.tv_phone});
view.setAdapter(sca);
}

 

 

方法3:自定义适配器

 

 


public class StudentAdapter extends BaseAdapter {//继承这个类:BaseAdapter


private List<Student> listStu;
private int myResouce;
private Context context;
public StudentAdapter(Context context_, List<Student> list, int resouce)//resouce表示给哪个view打气球
{
listStu = list;
myResouce = resouce;
context = context_;

}
@Override
public int getCount() {
return listStu.size();
}

@Override
public Object getItem(int position) {
return listStu.get(position);
}

@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)//如果不等于null就不用打气球了
{
convertView = convertView.inflate(context, myResouce, null);//开始打气球咯
}
Student st = listStu.get(position);
((TextView)convertView.findViewById(R.id.tv_name)).setText(st.getName());
((TextView)convertView.findViewById(R.id.tv_age)).setText(st.getAge()+"");
((TextView)convertView.findViewById(R.id.tv_phone)).setText(st.getPhone());
return convertView;//返回打好的气球
}

 

private void show3() {
DataBase d = new DataBase(this);
view.setAdapter(new StudentAdapter(this, d.GetAll_Fy(10, 20), R.layout.item));  //我喜欢这种方法,可以自由
}

 

posted @ 2014-05-04 02:10  宝贝,我永远都在  阅读(118)  评论(0)    收藏  举报