下面直接給出代碼:這個工具也包含了通過反射獲取對象、判斷是否存在某個類,在我們自定義控件的時候用到了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】