有時候因為程式的需求會需要用檔名來取得Resource id

import java.lang.reflect.Field;
public int getResId(String variableName, Class<?> c) {
	try {
		Field idField = c.getDeclaredField(variableName);
		return idField.getInt(idField);
	} catch (Exception e) {
		e.printStackTrace();
		return -1;
	}
}

 第一個參數是檔名,第二個參數是你要找的Resource class

getResId("filename", R.drawable.class)
創作者介紹
創作者 隨手寫寫 的頭像
Gohome

隨手寫寫

Gohome 發表在 痞客邦 留言(0) 人氣( 129 )