Android SimpleCursorAdapter设置图像

时间:2013-12-26 15:37:12

标签: android android-listview simplecursoradapter

以下是将数据设置到列表的代码:

ca = new ContactsAdapter();
        ca.open(getApplicationContext());

        c = ca.fetchAllContacts();

        startManagingCursor(c);

        if(c!=null){
            SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
                R.layout.contacts_row,
                c,
                new String[] {c.getColumnName(1), c.getColumnName(2)},
                new int[] {R.id.c_title,R.id.c_description});
            setListAdapter(adapter);
        }

我需要为每5行向ImageView附加不同的图像。图像不存储在DB中,它们存储在drawable文件夹中。我应该使用ViewBinder还是有更简单的方法?如果ViewBinder那么我应该如何修改呢?

 ViewBinder viewBinder = new ViewBinder() {

        public boolean setViewValue(View view, Cursor c, int columnIndex) {
        ImageView image = (ImageView)findViewById(R.id.img);

        Drawable myDrawable = getResources().getDrawable(R.drawable.pmuaiso);
        Bitmap bitimage = ((BitmapDrawable) myDrawable).getBitmap();

        image.setImageBitmap(bitimage);
        return true;

        }

谢谢。

1 个答案:

答案 0 :(得分:0)

您需要扩展SimpleCursorAdapter类。这是我的一个项目的片段:

public class CustomSimpleCursorAdapter extends SimpleCursorAdapter 
{
    public CustomSimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) 
    {
        super(context, layout, c, from, to, flags);

        this.setViewBinder(new ViewBinder() 
        {
            @Override
            public boolean setViewValue(View view, Cursor cursor, int columnIndex) 
            {
                switch(view.getId())
                {
                    case R.id.item_yyyy:
                    {
                        ((TextView) view).setTextColor(color);
                        ((TextView) view).setText(cursor.getString(cursor.getColumnIndex(DataBase.JURNAL_YEAR)));
                        break;
                    }
                    case R.id.item_mm:
                    {
                        ((TextView) view).setTextColor(color);
                        ((TextView) view).setText(cursor.getString(cursor.getColumnIndex(DataBase.JURNAL_MONTH)));
                        break;
                    }
                }
            }
        }
    }
}