is there any way to find resource Id of drawable

2020-03-08 09:17发布

Is there any way to get the Drawable resource ID? For example, I am using an ImageView and I may initially use icon.png as its image but later I may change the image to icon2.png. I want to find out using the code that which image my ImageView is using from the resource. Is there any way?

7条回答
Bombasti
2楼-- · 2020-03-08 09:41

There are a few steps to this:

  1. create integer-array xml to hold names of drawables (ie: "@drawable/icon1" ... "@drawable/iconN"

  2. use getIdentifier above to get the "array"

  3. with ID for list of drawable, getStringArray will give you an array names of drawables you specified in step 1.

  4. then use any of the drawable name in the array with getIdentifier again to get the drawable ID. This use "drawable" instead of "array" type.

  5. use this ID to set image for your view.

HOpe this will help.

查看更多
等我变得足够好
3楼-- · 2020-03-08 09:41

I now that the question is pretty old, but maybe someone will find it useful.

I have a list of TextViews with Drawables and want to set click listeners for all of them, without any need to change the code, when the layout is changed.

So I've put all drawables into a hashmap to get their ids later.

main_layout.xml

<LinearLayout android:id="@+id/list" >

    <TextView android:drawableLeft="@drawable/d1" />
    <TextView android:drawableLeft="@drawable/d2" />
    <TextView android:drawableLeft="@drawable/d3" />
    <TextView android:drawableLeft="@drawable/d4" />
    <!-- ... -->
</LinearLayout>

MyActivity.java

import java.lang.reflect.Field;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Drawable.ConstantState;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MyActivity extends Activity {

    private final HashMap<ConstantState, Integer> drawables = new HashMap<ConstantState, Integer>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main_layout);

        for (int id : getAllResourceIDs(R.drawable.class)) {
            Drawable drawable = getResources().getDrawable(id);
            drawables.put(drawable.getConstantState(), id);
        }

        LinearLayout list = (LinearLayout)findViewById(R.id.list);

        for (int i = 0; i < list.getChildCount(); i++) {

            TextView textView = (TextView)list.getChildAt(i);       
            setListener(textView);

        }
    }

    private void setListener(TextView textView) {

        // Returns drawables for the left, top, right, and bottom borders.
        Drawable[] compoundDrawables = textView.getCompoundDrawables();

        Drawable left = compoundDrawables[0];

        final int id = drawables.get(left.getConstantState());

        textView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent broadcast = new Intent();

                broadcast.setAction("ACTION_NAME");

                broadcast.putExtra("ACTION_VALUE", id);

                sendBroadcast(broadcast);
            }
        });
    }

    /**
     * Retrieve all IDs of the Resource-Classes
     * (like <code>R.drawable.class</code>) you pass to this function.
     * @param aClass : Class from R.X_X_X, like: <br>
     * <ul>
     * <li><code>R.drawable.class</code></li>
     * <li><code>R.string.class</code></li>
     * <li><code>R.array.class</code></li>
     * <li>and the rest...</li>
     * </ul>
     * @return array of all IDs of the R.xyz.class passed to this function.
     * @throws IllegalArgumentException on bad class passed.
     * <br><br>
     * <b>Example-Call:</b><br>
     * <code>int[] allDrawableIDs = getAllResourceIDs(R.drawable.class);</code><br>
     * or<br>
     * <code>int[] allStringIDs = getAllResourceIDs(R.string.class);</code>
     */
    private int[] getAllResourceIDs(Class<?> aClass) throws IllegalArgumentException {
            /* Get all Fields from the class passed. */
            Field[] IDFields = aClass.getFields();

            /* int-Array capable of storing all ids. */
            int[] IDs = new int[IDFields.length];

            try {
                    /* Loop through all Fields and store id to array. */
                    for(int i = 0; i < IDFields.length; i++){
                            /* All fields within the subclasses of R
                             * are Integers, so we need no type-check here. */

                            // pass 'null' because class is static
                            IDs[i] = IDFields[i].getInt(null);
                    }
            } catch (Exception e) {
                    /* Exception will only occur on bad class submitted. */
                    throw new IllegalArgumentException();
            }
            return IDs;
    }

}

Method getAllResourceIDs I've used from here

查看更多
ら.Afraid
4楼-- · 2020-03-08 09:45

This one is the best method to find out the R.drawablw.image1 value when u click on the ImageView in ur prgoram ,The method is some like that in main program first of all save the image value in the tag like that

public...activity 
{
//-----this vl store the drawable value in Tag of current ImageView,which v vl retriew in //image ontouchlistener event...
ImageView imgview1.setTag(R.drawable.img1);
ImageView imgview2.setTag(R.drawable.img2);

onTouchListnener event...
{

  ImageView imageView = (ImageView) v.findViewById(R.id.imgview1)v;
  Object tag = imageView.getTag();                  
  int id = tag == null ? -1 : Integer.parseInt(tag.toString());
switch(id)
{
case R.drawable.img1:
//do someoperation of ur choice
break;
case R.drawable.img2:
//do someoperation of ur choice
break:
    }//end of switch

 }//end of touch listener event

  }//end of main activity

               "PIR FAHIM SHAH/kpk uet mardan campus"
查看更多
叼着烟拽天下
5楼-- · 2020-03-08 09:49

Another approach : you just need to create your own customized view. and onCreate. then iterate the AttributeSet object(attrs) to find index of your attribute. then just call getAttributeResourceValue with index, then you will get initial ResouceID value. a simple example of extending ImageView to get ResourceID for background:

public class PhoneImageView extends ImageView {

    private static final String BACKGROUND="background";
    private int imageNormalResourceID;

    public PhoneImageView(Context context) {
        super(context);
    }

    public PhoneImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        for (int i = 0; i <attrs.getAttributeCount() ; i++) {
            if(attrs.getAttributeName(i).equals(BACKGROUND)){
                imageNormalResourceID =attrs.getAttributeResourceValue(i,-1);
            }
        }
    }

    public PhoneImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


}

This approach is suitable for who is looking to store initial values.. solution provided by Bojan Kseneman (+1 vote) is for keeping ref to resourceID whenever view is changed.

查看更多
Lonely孤独者°
6楼-- · 2020-03-08 09:53

You can get the id of an image with it's name by below code.

int drawableImageId = getResources().getIdentifier(imageName,"drawable", getPackageName());
查看更多
姐就是有狂的资本
7楼-- · 2020-03-08 09:55

Are you trying to determine what the current image is on the imageview, in order to change it to some other image?

If that's so I suggest doing everything using code instead of xml.

i.e. Use setImageResource() to set the initial images during initialization and keep track of the resource ids being used somewhere in your code.

For example, you can have an array of imageviews with a corresponding array of int that contains the resource id for each imageview

Then, whenever you want to change the image, loop through the array and see what the id is.

查看更多
登录 后发表回答