64

assetフォルダーから画像を読み込んで、 ImageView. これに を使用した方がはるかに優れていることR.id.*はわかっていますが、前提は、画像のIDがわからないことです。基本的に、ファイル名を介して画像を動的にロードしようとしています。

たとえば、 'cow'表すdatabase要素をランダムに取得すると、アプリケーションは. これは、 のすべての要素にも当てはまります。(仮定は、すべての要素に同等の画像があるということです)ImageViewdatabase

前もって感謝します。

編集

asset質問を忘れました。フォルダーから画像を読み込むにはどうすればよいですか?

4

8 に答える 8

127

このコードをチェックアウトしてください。このチュートリアルでは、アセット フォルダーから画像を読み込む方法を見つけることができます。

// 画像をロード

try 
{
    // get input stream
    InputStream ims = getAssets().open("avatar.jpg");
    // load image as Drawable
    Drawable d = Drawable.createFromStream(ims, null);
    // set image to ImageView
    mImage.setImageDrawable(d);
    ims .close();
}
catch(IOException ex) 
{
    return;
}
于 2012-07-31T07:05:22.977 に答える
52

はい、どうぞ、

  public Bitmap getBitmapFromAssets(String fileName) throws IOException {
    AssetManager assetManager = getAssets();

    InputStream istr = assetManager.open(fileName);
    Bitmap bitmap = BitmapFactory.decodeStream(istr);
    istr.close();

    return bitmap;
}
于 2012-07-31T07:09:02.983 に答える
32

コード内のファイル名がわかっている場合は、これを呼び出しても問題ありません。

ImageView iw= (ImageView)findViewById(R.id.imageView1);  
int resID = getResources().getIdentifier(drawableName, "drawable",  getPackageName());
iw.setImageResource(resID);

ファイル名は drawableName と同じ名前になるため、アセットを扱う必要はありません。

于 2012-07-31T07:04:59.627 に答える
7

これらの回答のいくつかは質問に答えるかもしれませんが、私はそれらのどれも好きではなかったので、これを書くことになりました.これはコミュニティの助けになります.

Bitmapアセットから取得:

public Bitmap loadBitmapFromAssets(Context context, String path)
{
    InputStream stream = null;
    try
    {
        stream = context.getAssets().open(path);
        return BitmapFactory.decodeStream(stream);
    }
    catch (Exception ignored) {} finally
    {
        try
        {
            if(stream != null)
            {
                stream.close();
            }
        } catch (Exception ignored) {}
    }
    return null;
}

Drawableアセットから取得:

public Drawable loadDrawableFromAssets(Context context, String path)
{
    InputStream stream = null;
    try
    {
        stream = context.getAssets().open(path);
        return Drawable.createFromStream(stream, null);
    }
    catch (Exception ignored) {} finally
    {
        try
        {
            if(stream != null)
            {
                stream.close();
            }
        } catch (Exception ignored) {}
    }
    return null;
}
于 2015-06-12T10:12:17.743 に答える