是否可以从assets文件夹加载drawable?

时间:2011-02-03 10:20:30

标签: android drawable assets

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

8 个答案:

答案 0 :(得分:105)

希望这有帮助:

Drawable d = Drawable.createFromStream(getAssets().open("Cloths/btn_no.png"), null);

答案 1 :(得分:7)

这是一个使用静态方法从类中获取drawable的类。它还会关闭输入流。

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;
    }
}

答案 2 :(得分:6)

我建议使用此

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

由于资源而返回正确缩放的drawable ......

答案 3 :(得分:2)

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

答案 4 :(得分:2)

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

检查返回的Drawable变量是否为null,因为如果路径无效或存在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;
}

答案 5 :(得分: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;
}

答案 6 :(得分:0)

我正在使用RecyclerView适配器,发现 David的答案对我不起作用((无论出于什么原因,asset.open仍然无法解析)

所以我发现这很适合我(科特琳代码)

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

这是我的目录,如您所见,资产从资产文件夹开始,这是关于如何创建该资产文件夹的link

enter image description here

答案 7 :(得分:-1)

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

看一下这个主题:Can the Android drawable directory contain subdirectories?

相关问题