Is it possible to load a drawable from the assets

2019-01-16 23:00发布

Can you load a drawable from a sub directory in the assets (not the drawable folder) folder?

7条回答
叼着烟拽天下
2楼-- · 2019-01-16 23:38

I recommend to use this

 Drawable.createFromResourceStream(resources,new TypedValue(), resources.getAssets().open(filename), null)

which returns properly scaled drawable thanks to resources ...

查看更多
Anthone
3楼-- · 2019-01-16 23:43

Hope this help:

Drawable d = Drawable.createFromStream(getAssets().open("Cloths/btn_no.png"), null);
查看更多
Emotional °昔
4楼-- · 2019-01-16 23:48

Here is function that does this for you.

Check the returned Drawable variable for null as null may return if the path is invalid or there is an IOException.

public static Drawable getDrawableFromAssetFolder(String fullPath, Activity ctx) {
    Drawable d =null;
    try {
        d = Drawable.createFromStream(ctx.getAssets().open(fullPath), null);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return d;
}
查看更多
smile是对你的礼貌
5楼-- · 2019-01-16 23:51

At this version you can't, if you make a sub folder within your drawable folder you can't use it in your xml file, it won't be recognized when you use android:src.

Take a look at this thread: Can the Android drawable directory contain subdirectories?

查看更多
可以哭但决不认输i
6楼-- · 2019-01-16 23:52

Yes you can create a Drawable object from an InputStream using the createFromStream() method.

查看更多
Emotional °昔
7楼-- · 2019-01-16 23:59

This helped getting the right density

private Drawable drawableFromAssetFilename(String filename) {
    AssetManager assetManager = mApplicationContext.getAssets();
    InputStream inputStream = null;
    try {
        inputStream = assetManager.open(filename);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

    BitmapDrawable drawable = new BitmapDrawable(mApplicationContext.getResources(), bitmap);
    return drawable;
}
查看更多
登录 后发表回答