How to Get the Resource Id of an Image If I Know Its Name

How to get a resource id with a known resource name?

It will be something like:

R.drawable.resourcename

Make sure you don't have the Android.R namespace imported as it can confuse Eclipse (if that's what you're using).

If that doesn't work, you can always use a context's getResources method ...

Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource);

Where this.context is intialised as an Activity, Service or any other Context subclass.

Update:

If it's the name you want, the Resources class (returned by getResources()) has a getResourceName(int) method, and a getResourceTypeName(int)?

Update 2:

The Resources class has this method:

public int getIdentifier (String name, String defType, String defPackage) 

Which returns the integer of the specified resource name, type & package.

How can I get an image resource by its name in Android?

The missing piece you are looking for is Resources.getIdentifier(). You can pass in the name as a String and get the integer identifier.

Resources | Android Developers

Example

long resId = parent.getResources().getIdentifier(arrayOfStrings[position], "drawable", mApplicationContext.getPackageName());

How to Get Image From Image Resource Id

hey there you are putting resource ID (intenger) as extra. and getting with string extra. make it as

        int resID =  data.getIntExtra("imgId",-1);
if(resID != -1 ){
Drawable img = getResources().getDrawable( resID );
img.setBounds( 0, 0, 60, 60 );

ed_operator.setCompoundDrawablesRelativeWithIntrinsicBounds( null, null, img, null );//if you dont have images already in drawable
//OR
ed_operator.setCompoundDrawables( null, null,img,null);//if you had set images in your drawable
}

How to get name of image with resourceid?

I hope you are looking for resource name from resource id. Use below api

   String name = getResources().getResourceEntryName(resid);

Trying to get drawable resource ID from its name in Android

One simple solution would be to parse the string and get only the image name as below.

String[] Image1 = array[1][1].split("/");
String s = Image1[Image1.length-1].replace(".png","").trim();

int resID = this.context.getResources().getIdentifier(s , "drawable", this.context.getPackageName());

How to get the id resource id of a view in a List view

For your ListView, you can set an onItemClickListener as below

ListView listView1 = (ListView) findViewById(R.id.listView1);
listView1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//With the position parameter, you can fetch the item at the clicked position like below.
AnimalsListItems yourItem = (AnimalsListItems) listView1.getItemAtPosition(position);
//Now you can assign the image to an imageview
}
}


Related Topics



Leave a reply



Submit