Android:ListView

来源:互联网 发布:安全知识网络答题活动 编辑:程序博客网 时间:2024/06/08 09:32

首先定义条目界面

<?xml version="1.0"encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 

android:orientation="horizontal" 

android:layout_width="fill_parent

android:layout_height="fill_parent">  

 <TextView 

android:layout_width="120dp" 

android:textSize="22sp" 

android:layout_height="wrap_content

android:id="@+id/name" />    

<TextView android:layout_width="150dp" 

 android:textSize="22sp" 

android:layout_height="wrap_content

android:id="@+id/phone" />  

 <TextView 

android:layout_width="fill_parent"  

android:textSize="22sp" 

android:layout_height="wrap_content

android:id="@+id/amount" /></LinearLayout>


public class MainActivity extends Activity {
    private ListView listView;
    private PersonService personService;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        personService = new PersonService(this);
        
        listView = (ListView) this.findViewById(R.id.listView);        listView.setOnItemClickListener(new ItemClickListener());        show2();    }        private final class ItemClickListener implements OnItemClickListener{        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {            ListView lView = (ListView)parent;            /* 自定义适配器            Person person = (Person) lView.getItemAtPosition(position);            Toast.makeText(getApplicationContext(), person.getId().toString(), 1).show();*/                        Cursor cursor = (Cursor) lView.getItemAtPosition(position);            int personid = cursor.getInt(cursor.getColumnIndex("_id"));            Toast.makeText(getApplicationContext(), personid+ "", 1).show();        }    }            //自定义适配器    private void show3() {        List<Person> persons = personService.getScrollData(0, 20);        PersonAdapter adapter = new PersonAdapter(this, persons, R.layout.item);        listView.setAdapter(adapter);    }    private void show2() {        Cursor cursor = personService.getCursorScrollData(0, 20);        //这个适配器的父类中说明了结果集必须含有_id字段:可以把表的主键改为_id,或者修改结果集使用别名的方式        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor,                new String[]{"name", "phone", "amount"}, new int[]{R.id.name, R.id.phone, R.id.amount});        listView.setAdapter(adapter);    }    private void show() {        List<Person> persons = personService.getScrollData(0, 20);        List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();        for(Person person : persons){            HashMap<String, Object> item = new HashMap<String, Object>();            item.put("name", person.getName());            item.put("phone", person.getPhone());            item.put("amount", person.getAmount());            item.put("id", person.getId());            data.add(item);        }        SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,                new String[]{"name", "phone", "amount"}, new int[]{R.id.name, R.id.phone, R.id.amount});                listView.setAdapter(adapter);            }


}



public class PersonService {
    private DBOpenHelper dbOpenHelper;

    public PersonService(Context context) {
        this.dbOpenHelper = new DBOpenHelper(context);
    }
    
    public void payment(){
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        db.beginTransaction();//开启事务
        try{
            db.execSQL("update person set amount=amount-10 where personid=1");
            db.execSQL("update person set amount=amount+10 where personid=2");
            db.setTransactionSuccessful();//设置事务的标志为True
        }finally{
            db.endTransaction();//结束事务,有两种情况:commit,rollback,
        //事务的提交或回滚是由事务的标志决定的,如果事务的标志为True,事务就会提交,否侧回滚,默认情况下事务的标志为False
        }
    }
    /**
     * 添加记录
     * @param person
     */
    public void save(Person person){
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        db.execSQL("insert into person(name, phone, amount) values(?,?,?)",
                new Object[]{person.getName(), person.getPhone(), person.getAmount()});
    }
    /**
     * 删除记录
     * @param id 记录ID
     */
    public void delete(Integer id){
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        db.execSQL("delete from person where personid=?", new Object[]{id});
    }
    /**
     * 更新记录
     * @param person
     */
    public void update(Person person){
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        db.execSQL("update person set name=?,phone=?,amount=? where personid=?",
                new Object[]{person.getName(), person.getPhone(),  person.getAmount(), person.getId()});
    }
    /**
     * 查询记录
     * @param id 记录ID
     * @return
     */
    public Person find(Integer id){
        SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from person where personid=?", new String[]{id.toString()});
        if(cursor.moveToFirst()){
            int personid = cursor.getInt(cursor.getColumnIndex("personid"));
            int amount = cursor.getInt(cursor.getColumnIndex("amount"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String phone = cursor.getString(cursor.getColumnIndex("phone"));
            return new Person(personid, name, phone, amount);
        }
        cursor.close();
        return null;
    }

    /**     * 分页获取记录     * @param offset 跳过前面多少条记录     * @param maxResult 每页获取多少条记录     * @return     */    public List<Person> getScrollData(int offset, int maxResult){        List<Person> persons = new ArrayList<Person>();        SQLiteDatabase db = dbOpenHelper.getReadableDatabase();        Cursor cursor = db.rawQuery("select * from person order by personid asc limit ?,?",                new String[]{String.valueOf(offset), String.valueOf(maxResult)});        while(cursor.moveToNext()){            int personid = cursor.getInt(cursor.getColumnIndex("personid"));            int amount = cursor.getInt(cursor.getColumnIndex("amount"));            String name = cursor.getString(cursor.getColumnIndex("name"));            String phone = cursor.getString(cursor.getColumnIndex("phone"));            persons.add(new Person(personid, name, phone, amount));        }        cursor.close();        return persons;    }    /**     * 分页获取记录     * @param offset 跳过前面多少条记录     * @param maxResult 每页获取多少条记录     * @return     */    public Cursor getCursorScrollData(int offset, int maxResult){        SQLiteDatabase db = dbOpenHelper.getReadableDatabase();        Cursor cursor = db.rawQuery("select personid as _id,name,phone,amount from person order by personid asc limit ?,?",                new String[]{String.valueOf(offset), String.valueOf(maxResult)});        return cursor;    }


    
    /**
     * 获取记录总数
     * @return
     */
    public long getCount(){
        SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select count(*) from person", null);
        cursor.moveToFirst();
        long result = cursor.getLong(0);
        cursor.close();
        return result;
    }
}



public class PersonAdapter extends BaseAdapter {private List<Person> persons;//在绑定的数据private int resource;//绑定的条目界面private LayoutInflater inflater;public PersonAdapter(Context context, List<Person> persons, int resource) {this.persons = persons;this.resource = resource;inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);}@Overridepublic int getCount() {return persons.size();//数据总数}@Overridepublic Object getItem(int position) {return persons.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {TextView nameView = null;TextView phoneView = null;TextView amountView = null;if(convertView==null){convertView = inflater.inflate(resource, null);//生成条目界面对象nameView = (TextView) convertView.findViewById(R.id.name);phoneView = (TextView) convertView.findViewById(R.id.phone);amountView = (TextView) convertView.findViewById(R.id.amount);ViewCache cache = new ViewCache();cache.nameView = nameView;cache.phoneView = phoneView;cache.amountView = amountView;convertView.setTag(cache);}else{ViewCache cache = (ViewCache) convertView.getTag();nameView = cache.nameView;phoneView = cache.phoneView;amountView = cache.amountView;}Person person = persons.get(position);//下面代码实现数据绑定nameView.setText(person.getName());phoneView.setText(person.getPhone());amountView.setText(person.getAmount().toString());return convertView;}private final class ViewCache{public TextView nameView;public TextView phoneView;public TextView amountView;}}




ListViewAdapter adapter实现将不同类型的数据进行转换,那个接口就被listview调用

lListViewAndroid开发过程中较为常见的组件之一,它将数据以列表的形式展现出来。一般而言,一个ListView由以下三个元素组成:

1View,用于展示列表,通常是一个xml所指定的。大家都知道Android的界面基本上是由xml文件负责完成的,所以ListView的界面也理所应当的使用了xml定义。例如在ListView中经常用到的“android.R.layout.simple_list_item等, 就是Android系统内部定义好的一个xml文件。

2、适配器,用来将不同的数据映射到View上。不同的数据对应不同的适配器,如BaseAdapterArrayAdapterCursorAdapterSimpleAdapter等, 他们能够将数组、指针指向的数据、Map等数据映射到View上。也正是由于适配器的存在,使得ListView的使用相当灵活,经过适配的处理后,在view看来所有的数据映射过来都是一样的。

3、数据,具体的来映射数据和资源,可以是字符串,图片等。通过适配器,这些数据将会被实现到ListView上。所有的数据和资源要显示到ListView上都通过适配器来完成。

l系统已有的适配器可以将基本的数据显示到ListView上,如:数组,Cursor指向的数据,Map里的数据。但是在实际开发中这些系统已实现的适配器,有时不能满足我们的需求。而且系统自带的含有多选功能ListView在实际使用过程中会有一些问题。要实现复杂的ListView可以通过继承ListView并重写相应的方法完成,同时也可以通过继承BaseAdapter来实现。
lBaseAdapterArrayAdapterCursorAdapterSimpleAdapter


lBaseAdapter需要重写的方法:
l       getCount(),
l       getItem(int position),
l       getItemId(intposition),
l       getView(int position, ViewconvertView,ViewGroup parent)
l       ListView在开始绘制的时候,系统首先调用getCount()函数,根据他的返回值得到listView的长度,然后根据这个长度,调用getView()逐一绘制每一行。如果你的getCount()返回值是0的话,列表将不显示同样return 1,就只显示一行。
l      系统显示列表时,首先实例化一个适配器(这里将实例化自定义的适配器)。当手动完成适配时,必须手动映射数据,这需要重写getView()方法。系统在绘制列表的每一行的时候将调用此方法。getView()有三个参数,position表示将显示的是第几行,covertView是从布局文件中inflate来的布局。我们用LayoutInflater的方法将定义好的item.xml文件提取成View实例用来显示。然后将xml文件中的各个组件实例化(简单的findViewById()方法)。这样便可以将数据对应到各个组件上了。但是按钮为了响应点击事件,需要为它添加点击监听器,这样就能捕获点击事件。至此一个自定义的listView就完成了,现在让我们回过头从新审视这个过程。系统要绘制ListView了,他首先获得要绘制的这个列表的长度,然后开始绘制第一行,怎么绘制呢?调用getView()函数。在这个函数里面首先获得一个View(实际上是一个ViewGroup),然后再实例并设置各个组件,显示之。好了,绘制完这一行了。那再绘制下一行,直到绘完为止。

public View getView(int position, ViewconvertView,ViewGroup parent){

 if (convertView == null){

convertView = mInflater.inflate(R.layout.item, null);

 }

 ((TextView)convertView.findViewById(R.id.text)).setText(DATA[position]);

((ImageView)convertView.findViewById(R.id.icon)).setImageBitmap((position& 1) == 1 ? mIcon1 : mIcon2);

returnconvertView; }

采用ViewHolder模式:

就是一个持有者的类,他里面一般没有方法,只有属性,作用就是一个临时的储存器,把你getView方法中每次返回的View存起来,可以下次再用。这样做的好处就是不必每次都到布局文件中去拿到你的View,提高了效率。

class ChatListAdapter extendsBaseAdapter {

static class ViewHolder {

TextView text;

ImageView icon;

}

public View getView(intposition, ViewconvertView,ViewGroup parent){

ViewHolder holder;

if (convertView == null){

convertView =mInflater.inflate(R.layout.list_item_icon_text, null);

holder = new ViewHolder();

holder.text = (TextView)convertView.findViewById(R.id.text);

holder.icon = (ImageView)convertView.findViewById(R.id.icon);

convertView.setTag(holder);

} else {

holder = (ViewHolder)convertView.getTag();

}

holder.text.setText(DATA[position]);

holder.icon.setImageBitmap((position& 1) == 1 ? mIcon1 : mIcon2);returnconvertView;

} }




0 0
原创粉丝点击