看一看API 直接API 1.这个方法用来使用资源名来获取资源ID 2.完整的资源名为package:type/entry,如果资源名这个参数有完整地指定,后面的defType和defPackage可以省略。 3.defType和defPackage省略时,需要将其设置成null 4.注意这个方法不提倡,因为直接通过资源ID访问资源会更加效率高 5.如果资源没有找到,返回0,在Android资源ID中0不是合法的资源ID。 复制代码 代码如下: ** * Return a resource identifier for the given resource name. A fully * qualified resource name is of the form "package:type/entry". The first * two components (package and type) are optional if defType and * defPackage, respectively, are specified here. * * <p>Note: use of this function is discouraged. It is much more * efficient to retrieve resources by identifier than by name. * * @param name The name of the desired resource. * @param defType Optional default resource type to find, if "type/" is * not included in the name. Can be null to require an * explicit type. * @param defPackage Optional default package to find, if "package:" is * not included in the name. Can be null to require an * explicit package. * * @return int The associated resource identifier. Returns 0 if no such * resource was found. (0 is not a valid resource ID.) */ public int getIdentifier(String name, String defType, String defPackage) { try { return Integer.parseInt(name); } catch (Exception e) { // Ignore } return mAssets.getResourceIdentifier(name, defType, defPackage); }
间接API 实际上上述API调用的是AssetManager.class中的native方法。 复制代码 代码如下: /** * Retrieve the resource identifier for the given resource name. */ /*package*/ native final int getResourceIdentifier(String type, String name, String defPackage);