get Id from res - Android App

Android examples for App:Resource

Description

get Id from res

Demo Code


//package com.java2s;
import java.lang.reflect.Field;
import android.content.Context;
import android.util.Log;

public class Main {
    private static Context ctx;

    public static int getId(Context context, String className,
            String fieldName) {//  w  w  w  .j  ava2 s.c o m
        try {
            String classz = getPackageName() + ".R$" + className;
            Class localClass = Class.forName(classz);
            Field localField = localClass.getField(fieldName);
            int i = Integer.parseInt(localField.get(localField.getName())
                    .toString());
            return i;
        } catch (Exception localException) {
            Log.e("getIdByReflection error", localException.getMessage());
        }

        return 0;
    }

    private static String getPackageName() {
        return ctx.getPackageName();
        //return "com.lostad.app";
    }
}

Related Tutorials