Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set an ImageViews source programmatically in Android? [duplicate]

Tags:

android

People also ask

How do I change the source of a picture on android?

Using setBackgroundResource() method: myImgView. setBackgroundResource(R.

Which file do you alter the image displayed by the ImageView in?

ImageView imageView = new ImageView(this); Bitmap bImage = BitmapFactory. decodeResource(this. getResources(), R. drawable.


I'd put the relation between Strings and images in a Map:

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("blah", R.drawable.blah);
// etc...

Then, you can use the setImageResource(int) method:

ImageView image;
image.setImageResource(map.get("blah"));

Or, if the strings have the same name than the image (like in the case before), you can load the resource by using this method: Android and getting a view with id cast as a string


Use setImageResource(int)


If I understand correctly, you want to display an image resource from a string. I do that in an app where the user can choose an image from a custom ListPreference and it is displayed in the MainActivity layout. The drawable resource ID is stored in the SharedPreferences as a string that matches the drawable resource ID (String) example: "@drawable/logo_image". I pull the value of the ListPreference with:

    SharedPreferences shared = getSharedPreferences("com.joshuariddle.recoveryworkscounter.settings", MODE_PRIVATE);
            String logo_id = (shared.getString("pref_logo",""));

This returns the drawable resource as a String i.e. @drawable/logo_image. Then to insert that drawable/image into my layout I use:

    ImageView iv_logo = (ImageView) findViewById(R.id.imgLogo);
    iv_logo.setImageResource(getResources().getIdentifier(logo_id, "drawable", "com.yourpackage"));

This will change the ImageView resource to the new drawable with setImageResource() using the int returned by the method below which returns an ID (int) from a string representing the drawable resource in com.yourpackage:

    getResources().getIdentifier(logo_id, "drawable", "com.yourpackage")

You can also use this same method to change other resources that use drawable such as Layout backgrounds etc. You just have to use this method to get the ID as an int:

    getResources().getIdentifier("Resource Id String", "drawable", "com.yourpackage")