Android 之优雅代码(一)——巧用assets

做一些和等级有关的应用时,我们经常需要使用一组图片资源,有以下几种调用方式


一、使用数组

int [] images = [ R.drawable.image1, R.drawable.image2, R.drawable.image3 ];

调用方式:

imageView.setBackgroundResource(images [index]);

优点:最直接高效的实现方案。如果把这些定义独立到一个全局常量文件里修改起来也相当方便。

           值得一提的是,如果图片文件仅有有限的几个,该方法无疑是最简单快捷的方法。

缺点:无法故弄玄虚,适合低级程序员。


二、使用array.xml

存放在res/values/array.xmlXML文件:

<?xml version="1.0" encoding="utf-8"?> 
<resources>  
<array name="images"> 
        <item>@drawable/image1</item> 
        <item>@drawable/image2</item> 
        <item>@drawable/image3</item> 
</array> 
</resources>

调用方式:

TypedArray typedArray = getResources().obtainTypedArray(R.array.images);
for(int i=0;i<typedArray.length();i++) {
	System.out.println(""+typedArray.getResourceId(i, 0));
}
typedArray.recycle();

优点:如果要添加或图片资源,无需修改代码,仅需要修改drawable中的相应图片资源和修改xml中的定义即可。

缺点:中高级程序员才会这么使用


三、使用assets

在assets/images中添加图片文件,格式如image1,png

AssetManager assetManager = getAssets();
try {
    InputStream is = assetManager.open("images/image"+index+".png");
<pre name="code" class="java">    Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close(); textView.setBackgroundDrawable(new BitmapDrawable(getResources(), bitmap));} catch (IOException e) { e.printStackTrace();}

优点:如果要添加或图片资源,无需修改代码,仅在assets中修改图片资源即可。

缺点:高级程序员才会想到这么使用



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值