【问题标题】:Get resource image by name into custom cursor adapter按名称获取资源图像到自定义光标适配器
【发布时间】:2012-03-04 00:05:38
【问题描述】:

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

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

【问题讨论】:

  • 如果您想从 Cursor 获取信息,为什么不致电 cursor.getString。您的图像存储在哪里?

标签: android android-listview android-imageview


【解决方案1】:

您只能对 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());

【讨论】:

  • 感谢“MH”。为解决方案。 (也适用于“MisterSquonk”)
  • 为什么可以使用 getResources() 而不在 Activity 中附加上下文?谢谢。
  • @Ricardo:因为Activity (indirectly) extends from Context。但是,没有什么可以阻止您编写 this.getResources(),这完全一样,但明确包含了调用它的对象(其中 this 是对 Activity 实例的引用,因此 @987654332 @)。
  • 谢谢@MH,我不知道。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多