开发者

Dynamically load Image in ImageView in Android

I have this database of 100+ images (of country flags) in my drawable folder.

Now I want to display the flag of the country you're currently in, in an ImageView.

I get the country with String country_variable = address.getCountryCode();

And I set the image with flag.setImageDrawable(getResources().getDrawable(R.drawable.country_variable));

As you all know R.drawable.country_variable wont't 开发者_如何学Gowork because the compiler can't find a image named country_variable in the drawable folder.

What is the best way to do this?


You should be able to use getResources().getIdentifier() to get the id by the resource name. Something like:

flag.setImageDrawable(getResources().getDrawable(getResources().getIdentifier("drawable/" + country_variable, "drawable", getPackageName()));


Try this:

flag.setImageDrawable(getResources().getDrawable(getResources().getIdentifier(country_variable, "drawable", getPackageName()));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜