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

问题描述:

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

希望这有助于:

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

在此版本中,如果您在可绘制文件夹中创建了一个子文件夹,但不能在xml文件中使用它,则在使用android:src时将无法识别它。

看看这个线程:Can the Android drawable directory contain subdirectories?

+0

既然如此,加载几百个自定义地图图块以显示在屏幕上的最简单方法是什么? – Jamie 2011-02-03 10:40:58

+0

啊我的问题是关于资产文件夹,而不是可绘制的。编辑的问题。 – Jamie 2011-02-03 11:18:40

+0

现在问题已经更新,此答案已过时。 – styler1972 2012-05-04 16:40:13

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

+0

对于可绘制文件夹中的可绘制对象是否也有可能?如果是,则比如何? – 2011-02-03 11:47:08

我建议使用此

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

返回适当的比例绘制得益于资源...

这有助于获得正确的密度

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

这是为你做这个的功能。

检查返回的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; 
} 

下面是一个静态方法从资产中获取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; 
    } 
}