[ACCEPTED]-Is it possible to load a drawable from the assets folder?-assets
Hope this help:
Drawable d = Drawable.createFromStream(getAssets().open("Cloths/btn_no.png"), null);
0
I recommend to use this
Drawable.createFromResourceStream(resources,new TypedValue(), resources.getAssets().open(filename), null)
which returns properly 1 scaled drawable thanks to resources ...
Here's a class with static method to get 2 the drawable from the assets. It also closes 1 the inputstream.
import android.content.Context;
import android.graphics.drawable.Drawable;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by bartburg on 4-11-2015.
*/
public class AssetsReader {
public static Drawable getDrawableFromAssets(Context context, String url){
Drawable drawable = null;
InputStream inputStream = null;
try {
inputStream = context.getAssets().open(url);
drawable = Drawable.createFromStream(inputStream, null);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return drawable;
}
}
Yes you can create a Drawable
object from an InputStream
using 1 the createFromStream() method.
Here is function that does this for you.
Check 3 the returned Drawable variable for null 2 as null may return if the path is invalid 1 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;
}
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;
}
0
I was working in a RecyclerView adapter 7 and found that David's answer was not working for 6 me, (for some reason asset.open
remained Unresolved 5 no matter what I imported )
so I found this 4 to work for me (Kotlin code)
val d = Drawable.createFromStream(context?.assets?.open("imageData/${imageName}.png"), null)
here is my directory, as 3 you can see the assets start from the assets 2 folder and here is a link on how to create that 1 assets folder
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.