listview(2、CursorAdapter)

CursorAdapter 适配器主要用以从数据库读取例子的场景,例子如下:

1. 定义一个adapter,继承CursorAdapter

复制代码
public class Adapter2 extends CursorAdapter {

    private int resourceid;
    private LayoutInflater mInflater = null;
    private TextView  title;
    private TextView  content;
    private ImageView image;
    
    public Adapter2(Context context, Cursor c, int id) {
        super(context, c, id);
        resourceid = id;
    }

    @Override
    public View newView(Context context, Cursor arg1, ViewGroup arg2) {
        mInflater = (LayoutInflater) context  
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = mInflater.inflate(resourceid, null);
        image   = (ImageView) view.findViewById(R.id.image);    
        title   = (TextView) view.findViewById(R.id.title);    
        content = (TextView) view.findViewById(R.id.content); 
                
        return view;
    }

    @Override
    public void bindView(View arg0, Context arg1, Cursor cursor) {
        image.setImageResource(R.drawable.ic_launcher);
        title.setText(cursor
                .getString(cursor.getColumnIndex("title")));
        content.setText(cursor
                .getString(cursor.getColumnIndex("content")));
    }

}
复制代码

2. 在activity中初始化测试数据,并关联这个适配器:

复制代码
public class MainActivity extends ListActivity {

    private SQLiteDatabase db;
    private final static String DB_NAME = "infos";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        
        
        initTestData();
        Cursor cursor = db.rawQuery("SELECT * FROM info", null);
        Adapter2 adapter = new Adapter2(this.getApplicationContext(), cursor,R.layout.item_list);
        this.setListAdapter(adapter);
        
        
    }
    
    public void initTestData(){
        db = openOrCreateDatabase(DB_NAME, this.MODE_PRIVATE, null);  
        db.execSQL("DROP TABLE IF EXISTS info");    
        db.execSQL("CREATE TABLE IF NOT EXISTS info (_id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR, content VARCHAR)");
        
        db.execSQL("INSERT INTO info VALUES (NULL,'标题A','暂无内容')"); 
        db.execSQL("INSERT INTO info VALUES (NULL,'标题B','暂无内容')");
        db.execSQL("INSERT INTO info VALUES (NULL,'标题C','暂无内容')");
        db.execSQL("INSERT INTO info VALUES (NULL,'标题D','暂无内容')");
        db.execSQL("INSERT INTO info VALUES (NULL,'标题E','暂无内容')");
    }
}
复制代码

备注:layout文件同baseAdapter例子。

 

posted @   Fredric_2013  阅读(239)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示