由资源名字找到ID

以下代码是在WallpaperChooser.java 中的加载Wallpaper的代码,

1.将图片名字写入到R.array.wallpaper中,保存一个壁纸的名字列表

2.将壁纸名字列表名字取出后,用

Stirng packageName = res.getResourcePackageName(R.array.wallpaper), 取到PackageName

int id =  res.getIdentifiier(name,"drawable",packageName) ;    取到ID值


 private void findWallpapers() {
        mThumbs = new ArrayList<Integer>(24);
        mImages = new ArrayList<Integer>(24);

        final Resources resources = getResources();
        // Context.getPackageName() may return the "original" package name,
        // com.android.launcher2; Resources needs the real package name,
        // com.android.launcher. So we ask Resources for what it thinks the
        // package name should be.
        final String packageName = resources.getResourcePackageName(R.array.wallpapers);

        addWallpapers(resources, packageName, R.array.wallpapers);
        addWallpapers(resources, packageName, R.array.extra_wallpapers);
    }

    private void addWallpapers(Resources resources, String packageName, int list) {
        final String[] extras = resources.getStringArray(list);
        for (String extra : extras) {
            int res = resources.getIdentifier(extra, "drawable", packageName);
            if (res != 0) {
                final int thumbRes = resources.getIdentifier(extra + "_small",
                        "drawable", packageName);

                if (thumbRes != 0) {
                    mThumbs.add(thumbRes);
                    mImages.add(res);
                    // Log.d(TAG, "addWallpapers: [" + packageName + "]: " + extra + " (" + res + ")");
                }
            }
        }
    }


你可能感兴趣的:(由资源名字找到ID)