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例子。

 

转载于:https://www.cnblogs.com/Fredric-2013/archive/2013/03/22/4357279.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值