-
Notifications
You must be signed in to change notification settings - Fork 34
/
ResourceUtil.java
110 lines (99 loc) · 2.72 KB
/
ResourceUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package com.liyi.sutils.utils;
import android.support.annotation.Nullable;
import com.liyi.sutils.R;
/**
* 资源相关工具类
*/
public class ResourceUtil {
/**
* 根据名称获取 Layout 的资源 Id
*
* @param resName Layout 的 xml 的名称
* @return
*/
public static int getLayoutByName(@Nullable String resName) {
return getIdByName("layout", resName);
}
/**
* 根据名称获取控件的资源 Id
*
* @param resName 控件的 Id 名称
* @return
*/
public static int getWidgetByName(@Nullable String resName) {
return getIdByName("id", resName);
}
/**
* 根据名称获取 Drawable 的资源 Id
*
* @param resName Drawable 的名称
* @return
*/
public static int getDrawableByName(@Nullable String resName) {
return getIdByName("drawable", resName);
}
/**
* 根据名称获取 Color 的资源 Id
*
* @param resName Color 的名称
* @return
*/
public static int getColorByName(@Nullable String resName) {
return getIdByName("color", resName);
}
/**
* 根据名称获取 Dimen 的资源 Id
*
* @param resName Dimen 的名称
* @return
*/
public static int getDimenByName(@Nullable String resName) {
return getIdByName("dimen", resName);
}
/**
* 根据名称获取 String 的资源 Id
*
* @param resName String 的名称
* @return
*/
public static int getStringByName(@Nullable String resName) {
return getIdByName("string", resName);
}
/**
* 根据名称获取 Style 的资源 Id
*
* @param resName Style 的名称
* @return
*/
public static int getStyleByName(@Nullable String resName) {
return getIdByName("style", resName);
}
/**
* 根据资源名称获取资源 Id
*
* @param className 资源类型
* @param resName 资源名称
* @return
*/
public static int getIdByName(@Nullable String className, @Nullable String resName) {
String packageName = SUtils.getApp().getPackageName();
int id = 0;
try {
Class r = Class.forName(packageName + ".R");
Class[] classes = r.getClasses();
Class desireClass = null;
for (Class cls : classes) {
if (cls.getName().split("\\$")[1].equals(className)) {
desireClass = cls;
break;
}
}
if (desireClass != null) {
id = desireClass.getField(resName).getInt(desireClass);
}
} catch (Exception e) {
e.printStackTrace();
}
return id;
}
}