I'm trying to set an imageView source based on a string within a custom ArrayAdapter, but I'm unable to get it to work. I know the object rec_gift is coming through correctly and the icon_string variable get's the correct name, but the setImageResource call isn't working.
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());
}
}
In the above code, I want to set the imageView based on the icon_string variable so each row in the listView will get the correct image but it's not making a change at all.
Implement getItem method of your custom adapter:
@Override
public Gift getItem(int position) {
if(this.giftz2 != null) {
this.giftz2.get(position);
} else {
return null;
}
}
And change this:
public int getImageId(String imageName) {
return context.getResources().getIdentifier("drawable/" + imageName, null, context.getPackageName());
}
To this:
public int getImageId(String imageName) {
return context.getResources().getIdentifier(imageName, "drawable", context.getPackageName());
}
And call method:
String icon_string = String.valueOf(rec_gift.photo_key);
iconz.setImageResource(getImageId(icon_string));
BTW: Try to reuse your views at your adapters getView method. If you continue using your implementation, you are going to get memory errors.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments