[ACCEPTED]-Android: Get the image source name of an ImageView to display on a TextView-android

Accepted answer
Score: 21

in xml you can add tag to set any information 3 with image

Example

<ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageview1" 
        android:background="@drawable/bg"
        android:tag="bg"/>

Dynamically you can use imageView.setTag("any name") to set 2 any data along with image and imageView.getTag() to retrieve 1 image information

String backgroundImageName = (String) imageView.getTag();
Score: 2

You can use below method for get name of 2 resource from it's id:

/**
         * Determines the Name of a Resource,
         * by passing the <code>R.xyz.class</code> and
         * the <code>resourceID</code> of the class to it.
         * @param aClass : like <code>R.drawable.class</code>
         * @param resourceID : like <code>R.drawable.icon</code>
         * @throws IllegalArgumentException if field is not found.
         * @throws NullPointerException if <code>aClass</code>-Parameter is null.                  
         * <code>String resName = getResourceNameFromClassByID(R.drawable.class, R.drawable.icon);</code><br>
         * Then <code>resName</code> would be '<b>icon</b>'.*/
        public String getResourceNameFromClassByID(Class<?> aClass, int resourceID)
                                                throws IllegalArgumentException{
                /* Get all Fields from the class passed. */
                Field[] drawableFields = aClass.getFields();

                /* Loop through all Fields. */
                for(Field f : drawableFields){
                        try {
                                /* All fields within the subclasses of R
                                 * are Integers, so we need no type-check here. */

                                /* Compare to the resourceID we are searching. */
                                if (resourceID == f.getInt(null))
                                        return f.getName(); // Return the name.
                        } catch (Exception e) {
                                e.printStackTrace();
                        }
                }
                /* Throw Exception if nothing was found*/
                throw new IllegalArgumentException();
        }

For Example of use 1 :

String resName = getResourceNameFromClassByID(R.drawable.class, R.drawable.icon);

Result will be icon

More Related questions