开发者

Can't use parseInt for images - Android

开发者 https://www.devze.com 2023-02-14 07:39 出处:网络
I have a problem with putting different images in a list. I created a custom list and everything worked fine, except the images issue.

I have a problem with putting different images in a list. I created a custom list and everything worked fine, except the images issue. My issue is with these line -

Integer p = Integer.parseInt("R.drawable.absolut");
holder.icon.setImageResource(p);

In the log I see the following error-

03-03 08:16:07.121: ERROR/Andro开发者_Python百科idRuntime(25486): java.lang.NumberFormatException: unable to parse 'R.drawable.absolut' as integer

What could cause this?

Thanks!


Parse int intended for parsing strings like "0", "100" etc and has nothing to do with what you're trying to achieve. You have to use the drawable id directly:

holder.icon.setImageResource(R.drawable.icon);

If for whatever reason you can't use the constant, correct way to get the drawable id would be:

Context context = getContext(); //obtain a context
int drawableId = context.getResources().getIdentifier("icon", "drawable", context.getPackageName());

But that's not a good practice at all and idicates that you have problems with your app design.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号