我正在尝试根据自定义 ArrayAdapter 中的字符串设置 imageView 源,但我无法让它工作。我知道对象 rec_gift 正确通过并且 icon_string 变量获得了正确的名称,但 setImageResource 调用不起作用。
public class MySimpleArrayAdapter extends ArrayAdapter<Gift> {
private final Context context;
private List<Gift> giftz2;
public MySimpleArrayAdapter(Context context, List<Gift> giftx) {
super(context, R.layout.listview_rowlayout, giftx);
this.context = context;
this.giftz2 = giftx;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.listview_rowlayout, parent, false);
ImageView iconz = (ImageView) rowView.findViewById(R.id.icon);
Gift rec_gift = (Gift) getItem(position);
String icon_string = "R.drawable." + rec_gift.photo_key;
iconz.setImageResource(getImageId(icon_string));
return rowView;
}
public int getImageId(String imageName) {
return context.getResources().getIdentifier("drawable/" + imageName, null, context.getPackageName());
}
}
在上面的代码中,我想根据 icon_string 变量设置 imageView,这样 listView 中的每一行都会获得正确的图像,但它根本没有进行任何更改。
最佳答案
实现自定义适配器的 getItem 方法:
@Override
public Gift getItem(int position) {
if(this.giftz2 != null) {
this.giftz2.get(position);
} else {
return null;
}
}
然后改变这个:
public int getImageId(String imageName) {
return context.getResources().getIdentifier("drawable/" + imageName, null, context.getPackageName());
}
对此:
public int getImageId(String imageName) {
return context.getResources().getIdentifier(imageName, "drawable", context.getPackageName());
}
以及调用方法:
String icon_string = String.valueOf(rec_gift.photo_key);
iconz.setImageResource(getImageId(icon_string));
顺便说一句:尝试在您的适配器 getView 方法中重用您的 View 。如果您继续使用您的实现,您将遇到内存错误。
关于java - 如何从自定义适配器动态设置 ListView 的 imageView 源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20021359/