2015-10-15 26 views
0

我试图编写加载图像或声音或其他类型的文件动态的代码。我想在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

你的输出是什么? – USKMobility

回答

2

声音尝试:

创建项目,并命名为“原始”的文件夹,并把声音文件夹

播放的声音:

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

图像我优先存储图像在可绘制的文件夹,并得到使用以下代码:

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