java - ImageView setBackround inside the activity dynamically -


inside drawabale folder have these images: levelone, leveltwo, level three.

i need set imageview according inputted string follows:

    levelindicatorimageview = (imageview) findviewbyid(r.id.levelindicatorimageview);      string tempo="r.drawable.level"+levelreached;     drawable replacer = getresources().getdrawable(tempo);     int sdk = android.os.build.version.sdk_int;     if(sdk < android.os.build.version_codes.jelly_bean) {         levelindicatorimageview.setbackgrounddrawable(replacer);     } else {         levelindicatorimageview.setbackground(replacer);     }     levelindicatorimageview.invalidate(); 

now inside levelreached variable have needed level (one, two, three) need set image r.drawable.leveltwo etc...

how possible please? getdrawable doesn't work tempo (needs int)

thanks help!

you have 2 options:

option 1:

simply use switch-case correct drawable, set background image would

// level drawable resource id int imageres = r.drawable.default_image; switch (levelreached) {     case level_one: // 1         imageres = r.drawable.level_one;         break;     case level_two: // 2         imageres = r.drawable.level_two;         break;     ... }  // set drawable background levelindicatorimageview.setbackgroundresource(imageres); 

where level_one == 1; level_two == 2; const or enum.

option 2:

you can find drawable resource name (as wanted), less recommended since more error prune. if must, use following example:

// level drawable resource id int imageres = getresources().getidentifier("level"+levelreached, "drawable", getpackagename());  // set drawable background levelindicatorimageview.setbackgroundresource(imageres); 

note:

you don't need explicitly invalidate view if set background since setting new background trigger invalidation itself. so, line:

levelindicatorimageview.invalidate(); 

is not needed.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -