Получить изображение ресурса по имени в пользовательский адаптер курсора - PullRequest
6 голосов
/ 04 марта 2012

У меня есть собственный адаптер курсора, и я хотел бы поместить изображение в ImageView в ListView.

Мой код:

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 Ответ

13 голосов
/ 04 марта 2012

Вы можете сделать вызов getResources() только для объекта Context. Поскольку конструктор 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());
...