Android 应用框架层调用应用层资源

自己在framework定义了一个组件但想调用应用层的图片资源方法如下:

在组件内用到的包

import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.content.pm.PackageManager.NameNotFoundException;

 实现过程如下:

try{
            PackageManager pm = context.getPackageManager();
            Resources resources = pm.getResourcesForApplication(应用包名);
            int id = resources.getIdentifier("资源名称", "资源类型", "应用包名");
        } catch (NameNotFoundException e) {
            Log.e(TAG, "package is not exists");
        }

getIdentifier (String name, String defType, String defPackage)API

public int getIdentifier (String name, String defType, String defPackage)
Since: API Level 1

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.

Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.
Parameters
name 	The name of the desired resource.
defType 	Optional default resource type to find, if "type/" is not included in the name. Can be null to require an explicit type.
defPackage 	Optional default package to find, if "package:" is not included in the name. Can be null to require an explicit package.
Returns

    * int The associated resource identifier. Returns 0 if no such resource was found. (0 is not a valid resource ID.) 

 

希望对大家能有帮助

猜你喜欢

转载自wpf814533631.iteye.com/blog/1266354
今日推荐