Android反射获取资源 id通用工具类

下面直接给出代码:这个工具也包含了通过反射获取对象、判断是否存在某个类,在我们自定义控件的时候用到了attrs,然而并没有直接获取该资源的反射,我们如果想获取styleable的话可以通过先获取style的id,取其0下标代表第一个类型。比如:

我在attrs中定义了一个控件属性:


一般的情况我们是通过

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircularProgress, defStyleAttr, 0);
这种方式获取styleable,在反射中我们可以通过

TypedArray a = context.obtainStyledAttributes(attrs, new int[]{ReflectUtil.getStyleId("CircularProgress")[0]}, defStyleAttr, 0);
方式获取。

package com.bojoy.ycsdktw.util;

import android.content.Context;

/**
 * @author luzhenyu
 * <p>资源反射类</p>
 * <li>getViewId - 获取控件id
 * <li>getLayoutId - 获取布局id
 * <li>getStringId - 获取字符串id 
 * <li>getDrawableId - 获取图片资源id
 * <li>getStyleId - 获取样式id
 * <li>getDimenId - 获取尺寸id
 * <li>getArrayId - 获取数组资源id
 * <li>getColorId - 获取颜色id
 * <li>getAnimId - 获取动画资源id
 * <li>isClassFounded - 判断类是否存在
 * <li>getObjectByClassName - 根据类名获取对象
 * */
public class ReflectUtil {
	
	private static int getResourceId(Context context, String name, String type) {
		int id = 0;
		id = context.getResources().getIdentifier(name, type, context.getPackageName());
		return id;
	}
	
	public static int getViewId(Context context, String name) {
		return getResourceId(context, name, "id");
	}
	
	public static int getLayoutId(Context context, String name) {
		return getResourceId(context, name, "layout");
	}
	
	public static int getStringId(Context context, String name) {
		return getResourceId(context, name, "string");
	}
	
	public static int getDrawableId(Context context, String name) {
		return getResourceId(context, name, "drawable");
	}
	
	public static int getStyleId(Context context, String name) {
		return getResourceId(context, name, "style");
	}
	
	public static int getDimenId(Context context, String name) {
		return getResourceId(context, name, "dimen");
	}
	
	public static int getArrayId(Context context, String name) {
		return getResourceId(context, name, "array");
	}
	
	public static int getColorId(Context context, String name) {
		return getResourceId(context, name, "color");
	}
	
	public static int getAnimId(Context context, String name) {
		return getResourceId(context, name, "anim");
	}
	
	public static boolean isClassFounded(String className)
	{
		try {
			@SuppressWarnings("unused")
			Class<?> aClass = Class.forName(className);
			return true;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public static Object getObjectByClassName(String className)
	{
		try {
			Class<?> aClass = Class.forName(className);
			return aClass.newInstance();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}
}

【欢迎上码】

【微信公众号搜索 h2o2s2】


猜你喜欢

转载自blog.csdn.net/luzhenyuxfcy/article/details/52225414
今日推荐