kis*_*idp 56 android assets image
我正在尝试从asset文件夹加载图像,然后将其设置为ImageView.我知道如果我使用这个更好R.id.*,但前提是我不知道图像的id.基本上,我试图通过其文件名动态加载图像.
例如,我随机检索元素的database代表,让我们说"牛",现在该怎么办我的应用程序会做的是显示的图像"牛"通过ImageView.对于所有元素也是如此database.(假设是,每个元素都有一个等价的图像)
提前致谢.
编辑
忘了这个问题,如何从asset文件夹中加载图像?
Chi*_*rag 110
查看此代码.在本教程中,您可以找到如何从资产文件夹加载图像.
//加载图片
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;
}
osa*_*gan 43
这个给你,
  public Bitmap getBitmapFromAssets(String fileName) {
    AssetManager assetManager = getAssets();
    InputStream istr = assetManager.open(fileName);
    Bitmap bitmap = BitmapFactory.decodeStream(istr);
    return bitmap;
}
Ero*_*rol 32
如果你知道代码中的文件名,那么调用它不会有问题:
ImageView iw= (ImageView)findViewById(R.id.imageView1);  
int resID = getResources().getIdentifier(drawableName, "drawable",  getPackageName());
iw.setImageResource(resID);
您的文件名将与drawableName同名,因此您不必处理资产.
其中一些答案可能会回答这个问题,但我从来没有喜欢过这些问题,所以我最终写了这个,这是我对社区的帮助.
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;
}
小智 5
根据Android 开发人员文档,使用位图加载可能会降低应用程序的性能。这是一个链接!所以文档建议使用Glide库。
如果你想从资源文件夹加载图像,那么使用Glide库可以帮助你更轻松。
只需将依赖项添加到https://github.com/bumptech/glide中的 build.gradle (Module:app)
 dependencies {
  implementation 'com.github.bumptech.glide:glide:4.9.0'
  annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
}
示例:
// For a simple view:
@Override public void onCreate(Bundle savedInstanceState) {
  ...
  ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
  Glide.with(this).load("file:///android_asset/img/fruit/cherries.jpg").into(imageView);
}
如果上述方法不起作用:将此对象替换为下面代码中的视图对象(仅当您在代码中应用了如下所示的 Inflate 方法时)。
 LayoutInflater mInflater =  LayoutInflater.from(mContext);
        view  = mInflater.inflate(R.layout.book,parent,false);
| 归档时间: | 
 | 
| 查看次数: | 81762 次 | 
| 最近记录: |