Gets resource ID of the resource - Android App

Android examples for App:Resource

Description

Gets resource ID of the resource

Demo Code


//package com.java2s;

import java.lang.reflect.Field;

public class Main {
    /**/*w  w  w. jav  a2  s. c o  m*/
     * Gets resource ID of the resource
     * @param resourceName  resource name
     * @param clazz an instance of Class, e.g. R.drawable.class
     * @return  an resource ID
     */
    public static int getId(String resourceName, Class<?> clazz) {
        try {
            Field idField = clazz.getDeclaredField(resourceName);
            return idField.getInt(idField);
        } catch (Exception e) {
            throw new RuntimeException("No resource ID found for: "
                    + resourceName + " / " + clazz, e);
        }
    }
}

Related Tutorials