本示例说明:
1.自定义listview条目样式,自定义listview显示列数的多少,灵活与数据库中字段绑定.
2.实现对DB的增删改查,并且操作后listview自动刷新.
3.响应用户操作点击事件,示例中展示单击时取出主键Id和其他内容.
4.响应用户操作长按事件,示例中展示长按时根据主键Id来编辑和删除数据.
5.表现层与数据处理层分开,不依赖于cursor(使用cursor不易表现和业务分离),支持接口编程.
6.使用数据库处理框架AHibernate灵活操作sqlite数据库,详见: http://blog.csdn.net/lk_blog/article/details/7455992
本示例效果图:
列出主要代码:
1.list.xml:
- <?xml version="1.0" encoding="UTF-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/child"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:background="#E3D25E"
- android:orientation="horizontal" >
- <!-- 若想隐藏id加入此属性: android:visibility="gone",这样做有点类似于Html中hidden域 -->
- <TextView
- android:id="@+id/idTo"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textColor="#ff0000" />
- <TextView
- android:id="@+id/nameTo"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:paddingBottom="5px"
- android:paddingLeft="50px"
- android:paddingTop="5px"
- android:text="No data"
- android:textColor="#0000ff"
- android:textSize="20sp" />
- <TextView
- android:id="@+id/ageTo"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:paddingBottom="5px"
- android:paddingLeft="50px"
- android:paddingTop="5px"
- android:text="No data"
- android:textColor="#00ff00"
- android:textSize="20sp" />
- </LinearLayout>
2.MainActivity.java:
- package com.tgb.lk.listview;
- import java.util.List;
- import java.util.Map;
- import com.tgb.lk.demo.dao.StudentDao;
- import com.tgb.lk.demo.dao.impl.StudentDaoImpl;
- import com.tgb.lk.demo.model.Student;
- import com.tgb.lk.listview.R;
- import android.app.Activity;
- import android.content.Context;
- import android.os.Bundle;
- import android.text.TextUtils;
- import android.view.ContextMenu;
- import android.view.MenuItem;
- import android.view.View;
- import android.view.ContextMenu.ContextMenuInfo;
- import android.view.View.OnClickListener;
- import android.widget.AdapterView;
- import android.widget.Button;
- import android.widget.ListView;
- import android.widget.SimpleAdapter;
- import android.widget.TextView;
- import android.widget.Toast;
- import android.widget.AdapterView.AdapterContextMenuInfo;
- import android.widget.AdapterView.OnItemClickListener;
- /**
- * 欢迎访问我的博客进行对代码交流: http://blog.csdn.net/lk_blog
- * 数据库处理使用AHibernate框架,详见:http://blog.csdn.net/lk_blog/article/details/7455992
- * @author likun
- */
- public class MainActivity extends Activity {
- private static final int ITEM_MODIFY = 1;
- private static final int ITEM_DELETE = 2;
- // 定义接口
- private StudentDao dao = null;
- private ListView lv = null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- // 添加
- Button btnAdd = (Button) findViewById(R.id.btnAdd);
- btnAdd.setOnClickListener(listener);
- // 显示前3条数据
- Button btnShow = (Button) findViewById(R.id.btnShow);
- btnShow.setOnClickListener(listener);
- // 删除数据
- Button btnClear = (Button) findViewById(R.id.btnClear);
- btnClear.setOnClickListener(listener);
- lv = (ListView) findViewById(R.id.lvStudent);
- // 设置在条目上单击监听器
- lv.setOnItemClickListener(itemListener);
- // 设置长按事件
- registerForContextMenu(lv);
- // 显示所有数据
- showData(-1);
- }
- // 显示数据,num小于等于0时显示所有数据,num大于0时显示前N条.
- private void showData(int num) {
- dao = (dao == null ? new StudentDaoImpl(this) : dao);
- List<Map<String, String>> data = null;
- if (num <= 0) { // 显示所有学生,调用dao层接口
- data = dao.queryAllStudent();
- } else {// 显示前N个学生,调用dao层接口
- data = dao.queryTopN(num);
- }
- SimpleAdapter adapter = buildListAdapter(this, data);
- lv.setAdapter(adapter);
- }
- // 构建adapter.
- public SimpleAdapter buildListAdapter(Context context,
- List<Map<String, String>> data) {
- SimpleAdapter adapter = new SimpleAdapter(context, data, R.layout.list,
- new String[] { "_id", "name", "age" }, new int[] { R.id.idTo,
- R.id.nameTo, R.id.ageTo });
- return adapter;
- }
- // 初始化数据
- OnClickListener listener = new OnClickListener() {
- @Override
- public void onClick(View v) {
- dao = (dao == null ? new StudentDaoImpl(MainActivity.this) : dao);
- switch (v.getId()) {
- case R.id.btnAdd:
- // 添加学生
- Student student1 = new Student();
- student1.setName("lk");
- student1.setAge(26);
- dao.insert(student1);
- Student student2 = new Student();
- student2.setName("cls");
- student2.setAge(26);
- dao.insert(student2);
- Student student3 = new Student();
- student3.setName("lb");
- student3.setAge(27);
- dao.insert(student3);
- showData(-1);
- break;
- case R.id.btnShow:
- // 显示前3条数据
- showData(3);
- break;
- case R.id.btnClear:
- // 删除所有数据
- dao.deleteData();
- // 显示所有数据
- showData(-1);
- break;
- default:
- break;
- }
- }
- };
- // 条目上单击处理方法.
- OnItemClickListener itemListener = new OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position,
- long id) {
- // 这里的view是我们在list.xml中定义的LinearLayout对象.
- // 所以可以通过findViewById方法可以找到list.xml中定义的它的子对象,如下:
- TextView stuId = (TextView) view.findViewById(R.id.idTo);
- TextView stuName = (TextView) view.findViewById(R.id.nameTo);
- TextView stuAge = (TextView) view.findViewById(R.id.ageTo);
- toastShow("学号:" + stuId.getText().toString() + "; 姓名:"
- + stuName.getText().toString() + "; 年龄:"
- + stuAge.getText().toString());
- }
- };
- // 封装Toast,一方面调用简单,另一方面调整显示时间只要改此一个地方即可.
- public void toastShow(String text) {
- Toast.makeText(MainActivity.this, text, 1000).show();
- }
- // 长按时显示的菜单
- @Override
- public void onCreateContextMenu(ContextMenu menu, View v,
- ContextMenuInfo menuInfo) {
- menu.setHeaderTitle("请选择操作");
- menu.add(0, ITEM_MODIFY, 0, "编辑");
- menu.add(0, ITEM_DELETE, 1, "删除");
- }
- // 响应编辑和删除事件处理
- public boolean onContextItemSelected(MenuItem item) {
- AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
- .getMenuInfo();
- // info.targetView得到list.xml中的LinearLayout对象.
- String stuId = ((TextView) info.targetView.findViewById(R.id.idTo))
- .getText().toString();
- if (!TextUtils.isEmpty(stuId)) {
- int id = Integer.parseInt(stuId);
- dao = (dao == null ? new StudentDaoImpl(this) : dao);
- switch (item.getItemId()) {
- case ITEM_MODIFY:
- // 编辑数据
- toastShow("编辑" + stuId);
- // 此方法定义在AHibernate中.更多使用示例见http://blog.csdn.net/lk_blog/article/details/7455992
- Student student = dao.get(id);
- student.setName("李坤");
- student.setAge(26);
- dao.update(student); // 此方法定义在AHibernate中.
- break;
- case ITEM_DELETE:
- // 删除数据
- toastShow("删除" + stuId);
- dao.delete(id);// 此方法定义在AHibernate中.
- break;
- default:
- break;
- }
- }
- showData(-1);
- return false;
- }
- }
3.数据库处理层:StudentDaoImpl.java:
- package com.tgb.lk.demo.dao.impl;
- import java.util.List;
- import java.util.Map;
- import com.tgb.lk.ahibernate.dao.impl.BaseDaoImpl;
- import com.tgb.lk.demo.dao.StudentDao;
- import com.tgb.lk.demo.model.Student;
- import com.tgb.lk.demo.util.DBHelper;
- import android.content.Context;
- //本文数据库处理引用jar包AHibernate处理.
- //AHibernate的详细使用教程示例地址: http://blog.csdn.net/lk_blog/article/details/7455992
- //AHibernate源码交流地址: http://blog.csdn.net/lk_blog/article/details/7456125
- //AHibernate jar包下载及源代码下载地址: http://download.csdn.net/detail/lk_blog/4222048
- public class StudentDaoImpl extends BaseDaoImpl<Student> implements StudentDao {
- public StudentDaoImpl(Context context) {
- super(new DBHelper(context));
- }
- // 返回一个List,List中的对象是以sql中的列的小写形式为key的Map.(本例中 _id,name,age为key)
- public List<Map<String, String>> queryAllStudent() {
- String sql = "select _id, name,age from t_student";
- return super.query2MapList(sql, null);
- }
- // 返回一个List,List中的对象是以sql中的列的小写形式为key的Map.(本例中 _id,name,age为key)
- public List<Map<String, String>> queryTopN(int num) {
- String sql = "select _id, name,age from t_student limit ?";
- return super.query2MapList(sql, new String[] { String.valueOf(num) });
- }
- public void deleteData() {
- String sql = "delete from t_student";
- super.execSql(sql, null);
- }
- }
最后,希望大家不吝赐教,对本文不足之处进行批评指正.