如何动态加载资产中的图像或声音?

时间:2015-10-15 16:35:13

标签: android

我正在尝试编写动态加载图像或声音或其他类型文档的代码。我想在ImageView中显示图像。我试过这个:

AssetManager assetManager = getAssets();
try {
    String[] imgPath = assetManager.list("img");
    for (int i = 0; i< imgPath.length; i++) {
        InputStream is = assetManager.open("img/"+imgPath[i]);
        Log.d(TAG, imgPath[i]);
        Bitmap  bitmap = BitmapFactory.decodeStream(is);

        imageViewbyCode = new ImageView(this);
        imageViewbyCode.setImageBitmap(bitmap);
        LinearLayout.LayoutParams params =  new LinearLayout
                        .LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        imageViewbyCode.setLayoutParams(params);
        myLayout.addView(imageViewbyCode);
    }
} catch (IOException e) {
    Log.e(TAG, e.getMessage());
}

1 个答案:

答案 0 :(得分:2)

声音尝试

在项目中创建一个文件夹,并将其命名为&#34; raw&#34;并将声音放在文件夹

播放声音:

   MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.your-sound);
   mp.start();

对于图像我更喜欢将图像存储在可绘制文件夹中并使用以下代码:

 Drawable drawable = getResources().getDrawable(getResources()
              .getIdentifier("imageName", "drawable", getPackageName()));