Android 利用SimpleCursorAdapter.ViewBinder 实现 List中标记Checkbox

摘要: Android Email app 来举个例子,这种app需要的基本功能中有 1. 从服务器接收的Email数据保存在本地数据库里面(SQLite) 2. Email数据中除了内容以外还会有一个boolean 变量(也可以用int 0/1 代替)来标记“已读”“未读”。

简单来说从SQLite里面读取已读变量,让系统在app中的List上画一个Checkbox。(根据SQLite里面的数据)

 

1. 首先定义一个 SimpleCursorAdapter.ViewBinder

 SimpleCursorAdapter.ViewBinder viewBinder = new SimpleCursorAdapter.ViewBinder() {
  
  @Override
  public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
   if(view instanceof CheckBox) {
    CheckBox checkbox = (CheckBox)view;
    int value = cursor.getInt(columnIndex);
    if(value==1) {
     checkbox.setChecked(true);
     return true;
    }
    else if(value==0) {
     checkbox.setChecked(false);
     return true;
    }
    else
     return false;
   }
   return false;
  }
 };

 

注:Cursor的可以有好几个行,这里的columnIndex表示一个行的索引。

 

2. 下面定义一个SimpleCursorAdapter本身 然后利用 SimpleCursorAdapter.setViewBinder()来套用之前定义的ViewBinder。

  SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this, R.layout.list_item,
    notificationCursor, new String[] { "subject", "content", "date", "unread"},
    new int[] {R.id.subject, R.id.content, R.id.date, R.id.unread});
  simpleCursorAdapter.setViewBinder(viewBinder);

注:这里的R.id.unread是指布局xml文件的里的CheckBox部件。 R.id.subject, R.id.content, R.id.date是其他Email数据。

  ListAdapter adapter = simpleCursorAdapter;

  setListAdapter(adapter); // Activity 是 ListActivity

3. 这样就完事了,下面的二行是ListAdapter的老规矩,简单吧。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值