android中的R中属性获取相关

1.根据R中属性的内存地址获取属性的名称:

     getString(R.string.app_name)

  

2. 根据R中属性的名称获取属性对应的内存地址:

getResources().getIdentifier("icon", R.drawable.class.getSimpleName(), R.class.getPackage().getName())

 

 

测试代码:

 

public class RSourceActivity extends Activity {
	private static final String TAG = "RSourceActivity";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.e(TAG, "===:" + getString(R.string.app_name));
        Log.e(TAG, "===:" +getRInt("icon"));
        Log.e(TAG, "===:" + getResources().getIdentifier("icon", R.drawable.class.getSimpleName(), R.class.getPackage().getName()));
    }
	
    /**
     * 根据R中资源的名称获取对应的内存地址
     * @param name
     * @return
     */
	private int getRInt(String name){
		Field[] fields = R.drawable.class.getDeclaredFields();
		for (Field field : fields) {
			if (field.getName().equals(name)) {
				try {
					return field.getInt(R.drawable.class);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return 0;
	}
}
 

你可能感兴趣的:(android)