获取图片的Drawable路径

Get Drawable path of images

我在我的 Fragment Activity 中实现了一个水平画廊,但我无法获取图像,因此返回 NullPointerException:

LinearLayout myGallery;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
    myGallery = (LinearLayout) getActivity().findViewById(R.id.mygallery);

    String targetPath = "assets/";

    Toast.makeText(getActivity(), targetPath, Toast.LENGTH_LONG).show();
    File targetDirector = new File(targetPath);

    File[] files = targetDirector.listFiles();
    for (File file : files){ //NullPointerException here
        myGallery.addView(insertPhoto(file.getAbsolutePath()));
    }
}

这是我图片的路径:

NullPointerException指向for循环for (File file ; files){ ...

到达我的文件夹的正确方法是什么?

正确的方法是...将您的图像放入 assets 文件夹(或 raw)。
不在 res.

创建 assets 文件夹(如果尚不存在)。
res 相同的水平不在其中

要获取您的资源,请使用类似这样的东西(在本例中,文件位于 gfx 文件夹下,在 assets 下):

final InputStream is = getApplicationContext().getAssets().open("gfx/" + fileName);
final Drawable drw = Drawable.createFromStream(is, null);

你的可绘制对象来自 assets


如果你想直接把资源放到assets而不是添加文件夹,只需更改这个

getApplicationContext().getAssets().open("gfx/" + fileName);

getApplicationContext().getAssets().open(fileName);