CursorAdapter 工作原理

ListView上下滚动,当需要显示一个新的ListItem的时候,Framework会调用 CursorAdapter 的getView 索取一个即将要显示的view。

如果CursorAdapter后台缓存里面有之前回收的view,则使用这个回收的view,如果没有回收的view可用,则调用newView来新建一个view。

之后再调用bindView将Cursor中的数据bind到这个将要显示的view中。

其调用顺序如下:

getView    ->    newView    ->    bindView

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CursorAdapter 是一个抽象类,你需要继承它并实现其中的一些方法,然后再创建一个实例对象。在这个实例对象中,你需要指定 item 的布局、绑定数据的字段、绑定数据的控件等信息。 下面是一个示例代码,假设你的 item 布局为 item_layout,其中有两个 TextView 分别显示 content 和 time,那么你的 adapter 可以这样设置: ``` public class NoteAdapter extends CursorAdapter { public NoteAdapter(Context context, Cursor cursor, int flags) { super(context, cursor, flags); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(context); return inflater.inflate(R.layout.item_layout, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView tvContent = view.findViewById(R.id.tv_content); TextView tvTime = view.findViewById(R.id.tv_time); String content = cursor.getString(cursor.getColumnIndex(DButil.CONTENT)); String time = cursor.getString(cursor.getColumnIndex(DButil.TIME)); tvContent.setText(content); tvTime.setText(time); } } ``` 在 onCreate 方法中,你可以这样初始化 adapter: ``` Cursor cursor = db.rawQuery("select * from note", null); adapter = new NoteAdapter(this, cursor, 0); lvselect.setAdapter(adapter); ``` 这样,当用户输入搜索关键词并提交时,你可以使用一个新的 Cursor 对象更新 adapter,然后调用 adapter 的 notifyDataSetChanged 方法通知界面更新: ``` private void selectquery(String query) { Cursor cursor = db.rawQuery("select * from note where content like ? or time like ?", new String[]{"%" + query + "%", "%" + query + "%"}); adapter.changeCursor(cursor); adapter.notifyDataSetChanged(); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值