Parsing error - Android java
I'm trying to fill a gridview dynamically with icons. I Followed the gridview hello tutorial. However the array with the images is not always exactly the same. Depending on the action before, a different image array
is given (extracted from soap response), which is constituted of the icon names, e.g. agenda => agenda.png. I wanted to create the array by looping through the array and adding it with R.drawable + icon_name
. However R.drawable
is not able to parse to the requested Integer array.
p开发者_如何学JAVAublic class ImageAdapter extends BaseAdapter
{
private Context mContext;
final ArrayList<String> image = getIntent().getStringArrayListExtra("image");
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return icoontjes.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public ArrayList<Integer> icoontjes;
{
for (int i=0; i<image.size(); i++){
Integer icon= Integer.valueOf("R.drawable."+image.get(i));
icoontjes.add(icon);
}
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(icoontjes.get(position));
return imageView;
}
}
You can use
for (int i=0; i < image.size(); i++) {
Integer icon = getResources().getIdentifier(image.get(i), "drawable", "your.package");
icoontjes.add(icon);
}
where your.package
is the base package of your android application (the package in which you have your static final R class
defined.
This way the icon
variable will hold the id of your drawable based on your image.get(i)
.
i can give u an answer but you shouldn't (really shouldn't) do this ...
instead of
Integer icon= Integer.valueOf("R.drawable."+image.get(i));
try
R.class.getField("R.drawable."+image.get(i)).getInt(null)
精彩评论