ListView 的使用

来源:互联网 发布:消防做题软件 编辑:程序博客网 时间:2024/05/17 19:19

一.一行布局

<?xmlversion="1.0"encoding="utf-8"?>

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

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="horizontal"

>

<!--android:gravity="center_vertical"文字垂直居中只设置一个,三个TextView都生效-->

<TextView

android:layout_width="100dp"

android:layout_height="40dp"

android:id="@+id/name"

android:gravity="center_vertical"

/>

<TextView

android:layout_width="100dp"

android:layout_height="40dp"

android:id="@+id/phone"

android:gravity="center_vertical"

/>

<TextView

android:layout_width="100dp"

android:layout_height="40dp"

android:id="@+id/amount"

android:gravity="center_vertical"

/>

</LinearLayout>


二.主Activity

主Activity包括一行的布局View

<?xmlversion="1.0"encoding="utf-8"?>

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

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical">


<LinearLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:orientation="horizontal">

<TextView

android:layout_width="100dp"

android:layout_height="30dp"

android:text="@string/name"

android:gravity="center_vertical"

/>

<TextView

android:layout_width="100dp"

android:layout_height="30dp"

android:text="@string/phone"

android:gravity="center_vertical"

/>

<TextView

android:layout_width="100dp"

android:layout_height="30dp"

android:text="@string/amount"

android:gravity="center_vertical"

/>

</LinearLayout>


<ListView

android:layout_width="fill_parent"

android:layout_height="fill_parent"

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


</LinearLayout>

三.MainActivity

packagecom.example.db;


importjava.util.ArrayList;

importjava.util.HashMap;

importjava.util.List;

importjava.util.Map;

importcom.example.adapter.PersonAdapter;

importcom.example.model.Person;

importcom.example.service.PersonService;

importandroid.os.Bundle;

importandroid.app.Activity;

importandroid.database.Cursor;

importandroid.view.Menu;

importandroid.view.View;

importandroid.widget.AdapterView;

importandroid.widget.AdapterView.OnItemClickListener;

importandroid.widget.ListView;

importandroid.widget.SimpleAdapter;

importandroid.widget.SimpleCursorAdapter;

importandroid.widget.Toast;


public class MainActivityextends Activity {

private ListViewlistView;

private PersonServicepersonService;


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

personService=new PersonService(this);

listView= (ListView)this.findViewById(R.id.listView);

listView.setOnItemClickListener(new ItemClickListener());

this.show();

//this.showUseCursor();

//this.showByCustom();


}


private final class ItemClickListenerimplements OnItemClickListener {


@Override

public void onItemClick(AdapterView<?> parent, View view, intindex,longid) {

ListView lView= (ListView) parent;

//对应自定义适配器

/*

* Personperson = (Person)lView.getItemAtPosition(index);

*//第二个参数必须为字符串,否则报错Toast.makeText(getApplicationContext(),

* "personId"+ person.getPersonId().toString(),

*Toast.LENGTH_SHORT).show();

*/


//对应Cursor适配器

/*

* Cursorcursor = (Cursor)lView.getItemAtPosition(index);int

* personId =cursor.getInt(cursor.getColumnIndex("_id"));

*Toast.makeText(getApplicationContext(), "personId"+ personId,

*Toast.LENGTH_SHORT).show();

*/


//对应SimpleAdapter适配器

@SuppressWarnings("unchecked")

Map<String,Object> map = (Map<String, Object>)lView.getItemAtPosition(index);

Object personId= map.get("id");

Toast.makeText(getApplicationContext(),"personId"+ personId, Toast.LENGTH_SHORT).show();

}


}


@Override

public boolean onCreateOptionsMenu(Menu menu) {

//Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.main,menu);

returntrue;

}


/**

*SimpleAdapter适配器

*/

private void show() {

List<Person> persons =newArrayList<Person>();

persons =personService.getScrollData(0,20);

List<Map<String,Object>> data =new ArrayList<Map<String, Object>>();

for(Person person : persons) {

Map<String,Object> personData =new HashMap<String, Object>();

personData.put("name",person.getName());

personData.put("phone",person.getPhone());

personData.put("amount",person.getAmount());

personData.put("id",person.getPersonId());

data.add(personData);

}

//值绑定到控件上,做好一对一关系

//

String[] values =new String[] { "name","phone","amount"};

//控件

int[] widgets =new int[]{ R.id.name,R.id.phone,R.id.amount};


//适配器

SimpleAdapter simpleAdapter =new SimpleAdapter(this,data, R.layout.item,values, widgets);

//

listView.setAdapter(simpleAdapter);

}


/**

*Cursor适配器

*/

private void showUseCursor(){

Cursor cursor =personService.getCursor(0,10);

//值绑定到控件上,做好一对一关系

//

String[] values =new String[] { "name","phone","amount"};

//控件

int[] widgets =newint[]{ R.id.name,R.id.phone,R.id.amount};

SimpleCursorAdapter simpleCursorAdapter =new SimpleCursorAdapter(this,R.layout.item,cursor,

values,widgets);

listView.setAdapter(simpleCursorAdapter);

//注:用这种方式会报一个错误java.lang.IllegalArgumentException:column '_id' does

//not exist

//解决方法

//1.在数据表中加入一个字段名叫"_id"

//2.在查询数据的时候使用别名

//例如"SELECTpersonidas _id, name, phone, amount FROM person ORDER BY personidASC LIMIT ?, ?";

}


/**

*自定义适配器

*/

private void showByCustom(){

List<Person> persons =new ArrayList<Person>();

persons = personService.getScrollData(0,10);

PersonAdapter personAdapter =new PersonAdapter(this,persons, R.layout.item);

listView.setAdapter(personAdapter);

}

}


四.Service

packagecom.example.service;


importjava.util.ArrayList;

importjava.util.List;

importandroid.content.Context;

importandroid.database.Cursor;

importandroid.database.sqlite.SQLiteDatabase;

importcom.example.model.Person;


publicclassPersonService {

privateDBOpenHelperdbOpenHelper;


publicPersonService(Context context) {

this.dbOpenHelper=newDBOpenHelper(context);

}


public void save(Person person) {

SQLiteDatabasedbOperate =dbOpenHelper.getWritableDatabase();

//采用占位符,防止sql注入

String sql ="INSERT INTO person(name, phone,amount) VALUES(?, ?, ?)";

Object[] params =newObject[] { person.getName(), person.getPhone(), person.getAmount() };

dbOperate.execSQL(sql,params);

}


public void delete(Integer id) {

SQLiteDatabasedbOperate =dbOpenHelper.getWritableDatabase();

String sql ="DELETE FROM person WHERE personid= ?";

Object[] params =newObject[] { id };

dbOperate.execSQL(sql,params);

}


public void update(Person person) {

SQLiteDatabase dbOperate =dbOpenHelper.getWritableDatabase();

String sql ="UPDATE person SET name = ?, phone= ?, amount = ? WHERE personid = ?";

Object[] params =new Object[] { person.getName(), person.getPhone(), person.getAmount(),

person.getPersonId()};

dbOperate.execSQL(sql,params);

}


publicPerson find(Integer id) {

//当数据库存储文件满的时候用dbOpenHelper.getReadableDatabase()得到的数据库实例只能读而不能写

//如果数据库存储文件没有满,那么得到的数据库存储实例和dbOpenHelper.getWritableDatabase()得到的一样

SQLiteDatabase dbOperate =dbOpenHelper.getReadableDatabase();

String sql ="SELECT * FROM person WHEREpersonid = ?";

String[] params =new String[] { String.valueOf(id)};

Cursor cursor =dbOperate.rawQuery(sql, params);

if(cursor.moveToFirst()) {

int personId = cursor.getInt(cursor.getColumnIndex("personid"));

String name =cursor.getString(cursor.getColumnIndex("name"));

String phone =cursor.getString(cursor.getColumnIndex("phone"));

int amount = cursor.getInt(cursor.getColumnIndex("amount"));

Person person =new Person(personId, name, phone, amount);

return person;

}

cursor.close();

return null;

}


public List<Person> getScrollData(int offset,int maxResult) {

List<Person> persons =new ArrayList<Person>();

SQLiteDatabase dbOperate =dbOpenHelper.getReadableDatabase();

String sql ="SELECT * FROM person ORDER BYpersonid ASC LIMIT ?, ?";

String[] params =new String[] { String.valueOf(offset),String.valueOf(maxResult)};

Cursor cursor =dbOperate.rawQuery(sql, params);

while(cursor.moveToNext()) {

int personId = cursor.getInt(cursor.getColumnIndex("personid"));

String name =cursor.getString(cursor.getColumnIndex("name"));

String phone =cursor.getString(cursor.getColumnIndex("phone"));

int amount = cursor.getInt(cursor.getColumnIndex("amount"));

Person person =new Person(personId, name, phone, amount);

persons.add(person);

}

cursor.close();

return persons;

}


public Cursor getCursor(int offset,int maxResult) {

SQLiteDatabasedbOperate =dbOpenHelper.getReadableDatabase();

String sql ="SELECT personid as _id, name,phone, amount FROM person ORDER BY personid ASC LIMIT ?, ?";

String[] params =new String[] { String.valueOf(offset),String.valueOf(maxResult)};

Cursor cursor =dbOperate.rawQuery(sql, params);

//不能关掉Cursor

return cursor;

}


public long getCount() {

SQLiteDatabasedbOperate =dbOpenHelper.getReadableDatabase();

String sql ="SELECT COUNT(*) FROM person";

Cursor cursor =dbOperate.rawQuery(sql,null);

cursor.moveToFirst();

long result = cursor.getLong(0);

return result;

}


public void payMent() {

SQLiteDatabasedbOperate =dbOpenHelper.getWritableDatabase();

//开启事务

dbOperate.beginTransaction();

try{

String sql2 ="update person set amount = amount- 10 where personid = 2";

String sql3 ="update person set amount = amount+ 10 where personid = 3";

dbOperate.execSQL(sql2);

dbOperate.execSQL(sql3);

//设置事务的标志为true

dbOperate.setTransactionSuccessful();

}finally{

//结束事务

//事务的提交或回滚是由事务的标志界定的,默认情况下事务的标志为false,如果事务的标志为true,事务就会回滚

dbOperate.endTransaction();

}


}

}


五.自定义适配器

packagecom.example.adapter;


importjava.util.List;

importcom.example.db.R;

importcom.example.model.Person;

importandroid.content.Context;

importandroid.view.LayoutInflater;

importandroid.view.View;

importandroid.view.ViewGroup;

importandroid.widget.BaseAdapter;

importandroid.widget.TextView;


publicclassPersonAdapterextendsBaseAdapter {

privateList<Person>persons;//绑定的数据

privateintacticity;//绑定的界面

privateLayoutInflaterlayoutInflater;//布局填充服务


publicPersonAdapter(Context context, List<Person> persons, intacticity) {

this.persons= persons;

this.acticity= acticity;

//取得布局填充服务

layoutInflater= (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}


@Override

publicintgetCount() {

returnpersons.size();

}


@Override

publicObject getItem(intindex) {

returnpersons.get(index);

}


@Override

publiclonggetItemId(intindex) {

returnindex;

}


//index该条目所在数据的索引值

@Override

publicView getView(intindex, View covertView, ViewGroup parent) {

TextView nameView =null;

TextView phoneView=null;

TextView amountView=null;

if(covertView ==null){//表示第一页

//创建View对象生成条目界面对象

covertView =layoutInflater.inflate(acticity,null);

nameView =(TextView) covertView.findViewById(R.id.name);

phoneView =(TextView) covertView.findViewById(R.id.phone);

amountView =(TextView) covertView.findViewById(R.id.amount);


//把获取的view缓存起来,第一次加载页面的时候缓存起来

ViewCacheviewCache =newViewCache();

viewCache.nameView= nameView;

viewCache.phoneView= phoneView;

viewCache.amountView= amountView;

covertView.setTag(viewCache);

}else{

//之后使用view就从缓存中取

ViewCacheviewCache = (ViewCache) covertView.getTag();

nameView =viewCache.nameView;

phoneView =viewCache.phoneView;

amountView =viewCache.amountView;

}


Person person =persons.get(index);

nameView.setText(person.getName());

phoneView.setText(person.getPhone());

amountView.setText(String.valueOf(person.getAmount()));


returncovertView;

}


privatefinalclassViewCache {

//使用public而不是用getset方法是为了减小文件大小,减少内存,提高效率

publicTextViewnameView;

publicTextViewphoneView;

publicTextViewamountView;

}

}