import java.lang.reflect.Field;
import android.util.Log;
public class ResourceUtil {
/**
* Finds the resource ID for the current application's resources.
* @param Rclass Resource class to find resource in.
* Example: R.string.class, R.layout.class, R.drawable.class
* @param name Name of the resource to search for.
* @return The id of the resource or -1 if not found.
*/
public static int getResourceByName(Class<?> Rclass, String name) {
int id = -1;
try {
if (Rclass != null) {
final Field field = Rclass.getField(name);
if (field != null)
id = field.getInt(null);
}
} catch (final Exception e) {
Log.e("GET_RESOURCE_BY_NAME: ", e.toString());
e.printStackTrace();
}
return id;
}
# 1 楼答案
可以通过在java中使用反射来实现这一点
如果你还不熟悉它,这里有一个很好的起点在programmcreek.com:
http://www.programcreek.com/2013/09/java-reflection-tutorial/
简单地说,作为一个例子,您可以使用以下示例代码在代码中迭代R:
此外,您可以参考以下问题了解更多信息: Android: Programatically iterate through Resource ids