有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (1) 个答案

  1. # 1 楼答案

    可以通过在java中使用反射来实现这一点

    如果你还不熟悉它,这里有一个很好的起点programmcreek.com

    http://www.programcreek.com/2013/09/java-reflection-tutorial/

    简单地说,作为一个例子,您可以使用以下示例代码在代码中迭代R:

    import java.lang.reflect.Field;
    
    import android.util.Log;
    
    public class ResourceUtil {
    
    /**
     * Finds the resource ID for the current application's resources.
     * @param Rclass Resource class to find resource in. 
     * Example: R.string.class, R.layout.class, R.drawable.class
     * @param name Name of the resource to search for.
     * @return The id of the resource or -1 if not found.
     */
    public static int getResourceByName(Class<?> Rclass, String name) {
        int id = -1;
        try {
            if (Rclass != null) {
                final Field field = Rclass.getField(name);
                if (field != null)
                    id = field.getInt(null);
            }
        } catch (final Exception e) {
            Log.e("GET_RESOURCE_BY_NAME: ", e.toString());
            e.printStackTrace();
        }
        return id;
    }
    

    此外,您可以参考以下问题了解更多信息: Android: Programatically iterate through Resource ids