Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Open resource from @drawable String

Tags:

android

I have:

 String uri = "@drawable/myresource.png"; 

How can I load that in ImageView? this.setImageDrawable?

like image 577
nikib3ro Avatar asked Feb 28 '10 01:02

nikib3ro


People also ask

How do you reference drawable android?

In your Android/Java source code you can also refer to that same image like this: Resources res = getResources(); Drawable drawable = res. getDrawable(R.

Which function is used is to load a drawable image resource?

Drawable myImage = ResourcesCompat. getDrawable(res, R. drawable. my_image, null);

What are Drawables in android?

A drawable resource is a general concept for a graphic that can be drawn to the screen and which you can retrieve with APIs such as getDrawable(int) or apply to another XML resource with attributes such as android:drawable and android:icon . There are several different types of drawables: Bitmap File.


2 Answers

If you really need to work with a string, try something like this:

private void showImage() {     String uri = "drawable/icon";      // int imageResource = R.drawable.icon;     int imageResource = getResources().getIdentifier(uri, null, getPackageName());      ImageView imageView = (ImageView) findViewById(R.id.myImageView);     Drawable image = getResources().getDrawable(imageResource);     imageView.setImageDrawable(image); } 

Else I would recommend you to work with R.* references like this:

int imageResource = R.drawable.icon; Drawable image = getResources().getDrawable(imageResource); 
like image 165
pfleidi Avatar answered Oct 16 '22 10:10

pfleidi


First, don't do that, as that @drawable syntax is meaningless in Java code. Use int resourceId=R.drawable.myresource.

If for some reason you do wind up a resource name and need the integer ID, use getIdentifier() on the Resources object.

like image 33
CommonsWare Avatar answered Oct 16 '22 08:10

CommonsWare