获取名称的可绘制标识符

时间:2016-05-10 17:08:05

标签: android

嗨,我找不到我的问题的解决方案。 我从db中取出图像的名称。然后我应该给image.setImageResource一个字符串。有很多答案,包括getResources().getIdentifier( 但getResoruces()不起作用。我得到的错误如下: 错误:(40,21)错误:找不到符号方法getResources()  我怎么能解决这个问题谢谢。

public class ReceivedItemAdapter extends ArrayAdapter<ReceivedItem> {

    public ReceivedItemAdapter(Context context, ArrayList<ReceivedItem> items){
        super(context,R.layout.row_item_received,items);
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        View customView = LayoutInflater.from(this.getContext())
            .inflate(R.layout.row_item_received, parent, false);

        ReceivedItem item = getItem(position);
        TextView textName = (TextView) customView.findViewById(R.id.nameTextView);
        TextView textCalorie = (TextView) customView.findViewById(R.id.calorieTextView);
        ImageView imageView = (ImageView) customView.findViewById(R.id.imageView);
        textName.setText(item.getName());
        textCalorie.setText(item.getCalorie()+ " cal");
        String mDrawableName = item.getImageName();
        int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
        imageView.setImageResource(resID);
        customView.setTag(item.getId());
        return customView;
    }
}

我在listview适配器类

中使用此代码

3 个答案:

答案 0 :(得分:1)

请在我们帮助您之前发布一些代码。

如果要访问外部和活动或类似的getResources,则需要获取对上下文的引用,然后调用context.getResources。

只需调用customView.getContext()。getResources()

答案 1 :(得分:1)

您需要将上下文实例保留在适配器中,然后调用context.getResources()

public class ReceivedItemAdapter extends ArrayAdapter<ReceivedItem> {

private final Context context;

public ReceivedItemAdapter(Context context, ArrayList<ReceivedItem> items){
    super(context,R.layout.row_item_received,items);
    this. context = context;
}

public View getView(int position, View convertView, ViewGroup parent) {

    View customView = LayoutInflater.from(this.getContext())
            .inflate(R.layout.row_item_received, parent, false);

    ReceivedItem item = getItem(position);
    TextView textName = (TextView) customView.findViewById(R.id.nameTextView);
    TextView textCalorie = (TextView) customView.findViewById(R.id.calorieTextView);
    ImageView imageView = (ImageView) customView.findViewById(R.id.imageView);
    textName.setText(item.getName());
    textCalorie.setText(item.getCalorie()+ " cal");
    String mDrawableName = item.getImageName();
    int resID = context.getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
    imageView.setImageResource(resID);
    customView.setTag(item.getId());
    return customView;
}

答案 2 :(得分:1)

这两个答案都是正确无误的。

但是打电话更容易

 int resID = customView.getContext().getResources().getIdentifier(mDrawableName , "drawable", getPackageName());

您可以这样做,因为每个视图都有对上下文的引用

  

public final Context getContext()

     

返回视图正在运行的上下文,它可以通过该上下文   访问当前主题,资源等

     

返回上下文视图的上下文。