get Layout Id from Resource - Android App

Android examples for App:Resource

Description

get Layout Id from Resource

Demo Code


//package com.java2s;

import java.lang.reflect.Field;
import java.util.HashMap;
import android.content.Context;

import android.content.res.Resources;
import android.util.SparseArray;

public class Main {
    private static HashMap<String, Integer> layoutIds;
    private static SparseArray<String> layoutNames;

    public static int getLayoutId(Context ctx, Resources res, String name)
            throws Exception {
        if (layoutIds == null) {
            getLayoutName(ctx, res, 0);// www  .j av a 2s  . co  m
        }
        Integer i = layoutIds.get(name);
        return i == null ? 0 : i.intValue();
    }

    public static String getLayoutName(Context ctx, Resources res, int id)
            throws Exception {
        if (layoutIds == null || layoutNames == null) {
            HashMap<String, Integer> map = new HashMap<String, Integer>();
            SparseArray<String> map2 = new SparseArray<String>();

            String rClazz = ctx.getPackageName() + ".R.layout";
            Class<?> r = ctx.getClassLoader().loadClass(rClazz);
            for (Field f : r.getDeclaredFields()) {
                if (java.lang.reflect.Modifier.isStatic(f.getModifiers())
                        && f.getType() == Integer.TYPE) {
                    Integer val = (Integer) f.get(null);
                    map.put(f.getName(), val.intValue());
                    map2.put(val.intValue(), f.getName());
                }
            }

            layoutIds = map;
            layoutNames = map2;
        }

        return layoutNames.get(id);
    }
}

Related Tutorials