按名称获取资源图像到自定义游标适配器

时间:2012-03-04 00:05:38

标签: android android-listview android-imageview

我有一个自定义游标适配器,我想将一个图像放入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);
  }
}

这一切都还可以,但我想从数据库(光标)获取图像的名称。 我试过

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

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

1 个答案:

答案 0 :(得分:13)

您只能对Context对象进行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());