AssetManager主要用于存储一些常用的资源,供项目使用。比如存放图片,Json文件,TextView自定义字体等等资源。下面讲解一下每个资源的使用方法。
1.获取使用图片
private Bitmap getImageFromAssetsFile(String fileName) {
Bitmap image = null;
AssetManager am = getResources().getAssets();
try {
InputStream is = am.open(fileName);
image = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
ImageView imageView=findViewById(R.id.activity_event_imageview);
imageView.setImageBitmap(getImageFromAssetsFile("img_3.jpg"));
2.获取使用Json文件
public static String getJson(String fileName, Context context) {
StringBuilder stringBuilder = new StringBuilder();
try {
//获取assets资源管理器
AssetManager assetManager = context.getAssets();
//通过管理器打开文件并读取
BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
String line;
while ((line = bf.readLine()) != null) {
stringBuilder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
String result = getJson("Two.json", this);
Log.d("TAG","result----:"+result);
3.获取assets目录下的文件设置TextView字体
AssetManager assetManager = activity.getAssets();
Typeface typeface = Typeface.createFromAsset(assetManager, "XXX路径/XXX.ttf");
textView.setTypeface(typeface);