Android中利用Drawable实现图片循环
2016-04-16 23:05
603 查看
通过使用Drawable来获取存储在assets目录下的图片实现:
1. 获取AssetManager
2. 创建数组并将获取到文件名存放到数组中
3. 读取图片文件
4. 打开图片的输入流
5. 从输入流中读取并改变图片
6. 回收图片
1. 获取AssetManager
2. 创建数组并将获取到文件名存放到数组中
3. 读取图片文件
4. 打开图片的输入流
5. 从输入流中读取并改变图片
6. 回收图片
步骤:
1.在布局中加入一个ImageView
2.在代码文件中进行读取
代码文件public class MainActivity extends Activity { String[] images = null; AssetManager assets = null; int currentImg = 0; ImageView image; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); image = (ImageView) findViewById(R.id.image); try { assets = getAssets(); // 获取/assets/目录下所有文件 images = assets.list(""); } catch (IOException e) { e.printStackTrace(); } // 获取next按钮 final Button next = (Button) findViewById(R.id.next); // 为next按钮绑定事件监听器,该监听器将会查看下一张图片 next.setOnClickListener(new OnClickListener() { @Override public void onClick(View sources) { // 如果发生数组越界 if (currentImg >= images.length) { currentImg = 0; } // 找到下一个图片文件 while (!images[currentImg].endsWith(".png") && !images[currentImg].endsWith(".jpg") && !images[currentImg].endsWith(".gif")) { currentImg++; // 如果已发生数组越界 if (currentImg >= images.length) { currentImg = 0; } } InputStream assetFile = null; try { // 打开指定资源对应的输入流 assetFile = assets.open(images[currentImg++]); } catch (IOException e) { e.printStackTrace(); } BitmapDrawable bitmapDrawable = (BitmapDrawable) image.getDrawable(); // 如果图片还未回收,先强制回收该图片 if (bitmapDrawable != null&& !bitmapDrawable.getBitmap().isRecycled()) { bitmapDrawable.getBitmap().recycle(); } // 改变ImageView显示的图片 image.setImageBitmap(BitmapFactory.decodeStream(assetFile)); } }); } }
相关文章推荐
- android开发--searchView
- Android 强制横屏
- Activity AndroidManifest的启动模式
- Android使用SharedPreferences保存HashSet<String>数据不能更新成功
- Android学习笔记4 图片和杂谈
- android studio 2.0加载so文件的方法
- Android动画学习笔记-Android Animation
- Android Studio系列教程四--Gradle基础
- android 文件存储读取
- android中的context究竟是什么?
- android NDK
- 帧动画
- android 硬件知识-传感器,无线电,和媒体功能的开发
- android------关于API 23的权限问题
- Android学习笔记(35):Android活动条
- Android中的布局
- androidStudio去除标题
- Android Binder机制分析(4) Parcel类分析
- Near Field Communication(nfc近场通信)——翻译自developer.android.com
- Android 开发之集成百度地图的定位与地图展示