使用Bitmap遍历Assets目录下图片
16lz
2021-01-26
布局文件:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btn" android:text="change img"/> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/img"/></LinearLayout>
java代码:
package com.example.android_test;import java.io.IOException;import java.io.InputStream;import android.app.Activity;import android.content.res.AssetManager;import android.graphics.BitmapFactory;import android.graphics.drawable.BitmapDrawable;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;public class AssetTest extends Activity {Button button;ImageView image;AssetManager manager=null;String[] images=null;int currentImg=0;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.asset_layout);button=(Button) findViewById(R.id.btn);image=(ImageView) findViewById(R.id.img);try {//获取资源manager=getAssets();//获取该目录下所有文件images=manager.list("");for (int i = 0; i < images.length; i++) {System.out.println(images[i]);}} catch (IOException e) {e.printStackTrace();}button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {for (;;) {System.out.println("当前文件:"+images[currentImg]+currentImg);//遍历文件为以后缀为".jpg"的文件if (images[currentImg].endsWith(".jpg")) {if (currentImg>=images.length) {currentImg=0;}InputStream in=null;try {//打开一个输入流in=manager.open(images[currentImg]);} catch (IOException e) {e.printStackTrace();}BitmapDrawable bitmapDrawable=(BitmapDrawable) image.getDrawable();//如果图片还未回收,强制回收if (bitmapDrawable!=null && !bitmapDrawable.getBitmap().isRecycled()) {System.out.println("bitmapDrawable!=null:"+(bitmapDrawable!=null)+"..."+"!bitmapDrawable.getBitmap().isRecycled():"+(!bitmapDrawable.getBitmap().isRecycled()));bitmapDrawable.getBitmap().recycle();}else {System.out.println("空的...");}image.setImageBitmap(BitmapFactory.decodeStream(in));currentImg++;break;}else {currentImg++;}if (currentImg>=images.length) {currentImg=0;}}}});}}
更多相关文章
- android canvas 编辑bitmap画虚线
- Android(安卓)adb setuid提权漏洞之分析
- init.rc 中on propert: 触发无效
- Android(安卓)LayoutInflater详解
- 改变滚动条的颜色ScrollView
- Application 判断 是否在主进程、主线程
- react native android环境配置
- 淘宝:模拟实现帮助提示页面
- Android(SpreadTurm)获取屏幕亮度,再设置屏幕亮度