2012-03-04 34 views
6

我有一个自定义的光标适配器,我想将图像放入ListView中的ImageView。通过名称获取资源图像到自定义光标适配器

我的代码是:

public class CustomImageListAdapter extends CursorAdapter { 

    private LayoutInflater inflater; 

    public CustomImageListAdapter(Context context, Cursor cursor) { 
    super(context, cursor); 
    inflater = LayoutInflater.from(context); 
    } 

    @Override 
    public void bindView(View view, Context context, Cursor cursor) { 
    // get the ImageView Resource 
    ImageView fieldImage = (ImageView) view.findViewById(R.id.fieldImage); 
    // set the image for the ImageView 
    flagImage.setImageResource(R.drawable.imageName); 
    } 

    @Override 
    public View newView(Context context, Cursor cursor, ViewGroup parent) { 
    return inflater.inflate(R.layout.row_images, parent, false); 
    } 
} 

这是一切OK,但我想从数据库(光标)获取图像的名称。 我试着用

String mDrawableName = "myImageName"; 
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName()); 

但返回错误:“该方法getResources()是未定义的类型CustomImageListAdapter”

+0

如果你想从光标获得,为什么不改用'cursor.getString'。你的图像存储在哪里? – 2012-03-04 00:20:25

回答

13

你只能做一个上下文对象上调用getResources()。由于CursorAdapter的构造函数需要这样的引用,因此只需创建一个可以跟踪它的类成员,以便可以在(可能)bindView(...)中使用它。您也可能需要它以获得getPackageName()

private Context mContext; 

public CustomImageListAdapter(Context context, Cursor cursor) { 
    super(context, cursor); 
    inflater = LayoutInflater.from(context); 
    mContext = context; 
} 

// Other code ... 

// Now call getResources() on the Context reference (and getPackageName()) 
String mDrawableName = "myImageName"; 
int resID = mContext.getResources().getIdentifier(mDrawableName , "drawable", mContext.getPackageName()); 
+0

+1你击败了我。 :) – Squonk 2012-03-04 00:20:56

+0

感谢“MH。”为解决方案。 (也给“MisterSquonk”) – Cuarcuiu 2012-03-04 13:32:26

+0

为什么你可以使用getResources()而不在活动内附加上下文?谢谢。 – Ricardo 2015-01-13 15:02:22

相关问题