46

assets您可以从(不是可绘制文件夹)文件夹中的子目录加载可绘制对象吗?

4

8 回答 8

107

希望这有帮助:

Drawable d = Drawable.createFromStream(getAssets().open("Cloths/btn_no.png"), null);
于 2011-02-22T19:07:21.307 回答
8

我建议使用这个

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

由于资源,它返回了适当缩放的可绘制对象......

于 2011-05-01T15:32:55.123 回答
7

这是一个具有静态方法的类,用于从资产中获取可绘制对象。它还关闭输入流。

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;
    }
}
于 2015-11-04T13:24:19.720 回答
2

是的,您可以使用createFromStream()方法Drawable从一个对象创建一个对象。InputStream

于 2011-02-03T11:26:08.997 回答
2

这是为您执行此操作的功能。

检查返回的 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;
}
于 2015-10-06T18:49:48.737 回答
0

这有助于获得正确的密度

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;
}
于 2015-05-07T11:21:43.173 回答
0

我在 RecyclerView 适配器中工作,发现David 的答案对我不起作用,(由于某种原因,asset.open无论我导入什么,都仍然未解决)

所以我发现这对我有用(Kotlin 代码)

val d = Drawable.createFromStream(context?.assets?.open("imageData/${imageName}.png"), null)

这是我的目录,您可以看到资产从资产文件夹开始,这是有关如何创建资产文件夹的链接

在此处输入图像描述

于 2020-04-21T12:48:41.997 回答
-1

在这个版本你不能,如果你在你的drawable文件夹中创建一个子文件夹你不能在你的xml文件中使用它,当你使用android:src时它不会被识别。

看一下这个线程:Android drawable 目录可以包含子目录吗?

于 2011-02-03T10:32:21.963 回答