[英]Is it possible to load a drawable from the assets folder?
您可以從assets
(不是可繪制文件夾)文件夾中的子目錄加載可繪制對象嗎?
希望這有幫助:
Drawable d = Drawable.createFromStream(getAssets().open("Cloths/btn_no.png"), null);
我建議使用這個
Drawable.createFromResourceStream(resources,new TypedValue(), resources.getAssets().open(filename), null)
由於資源,它返回適當縮放的可繪制對象......
這是一個帶有靜態方法的類,用於從資產中獲取可繪制對象。 它還關閉輸入流。
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;
}
}
這是為您執行此操作的功能。
檢查返回的 Drawable 變量是否為 null,因為如果路徑無效或存在 IOException,則可能返回 null。
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;
}
是的,您可以使用createFromStream()方法從InputStream
創建一個Drawable
對象。
這有助於獲得正確的密度
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;
}
我在 RecyclerView 適配器中工作,發現David 的回答對我不起作用,(由於某種原因,無論我導入什么, asset.open
仍然未解決)
所以我發現這對我有用(Kotlin 代碼)
val d = Drawable.createFromStream(context?.assets?.open("imageData/${imageName}.png"), null)
這是我的目錄,您可以看到資產從資產文件夾開始,這里是有關如何創建該資產文件夾的鏈接
在這個版本你不能,如果你在你的 drawable 文件夾中創建一個子文件夾你不能在你的 xml 文件中使用它,當你使用 android:src 時它不會被識別。
看看這個線程: Android drawable 目錄可以包含子目錄嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.