读取assets目录下的图片文件
发布日期:2021-06-30 21:07:27 浏览次数:4 分类:技术文章

本文共 2096 字,大约阅读时间需要 6 分钟。

1.layout

2.java

public class MainActivity extends AppCompatActivity {    String[] images = null;    AssetManager assets = null;    int currentImg = 0;    ImageView image;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        /*Bitmap b = new Bitmap();        BitmapDrawable bd = new BitmapDrawable(b);        Bitmap a = bd.getBitmap();*/        image = (ImageView) findViewById(R.id.imag);        try{            assets = getAssets();            images = assets.list("");//参数为文件夹的名字,空就是所有文件.返回指定路径下的所有文件及目录名string数组        } catch (Exception e){            Log.i("mydate" , "错误1");        }        Button next = (Button) findViewById(R.id.next);        next.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                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{                    //assets下的文件只能读(用open打开inputsream),不能写                    assetFile = assets.open(images[currentImg++]);                } catch (Exception e){                    Log.i("mydate" , "错误2");                }                //得到image的图片                BitmapDrawable bitmapDrawable = (BitmapDrawable) image.getDrawable();                //先回收之前那张图片                if (bitmapDrawable != null && !bitmapDrawable.getBitmap().isRecycled()){                    bitmapDrawable.getBitmap().recycle();                }                //设置新的图片                image.setImageBitmap(BitmapFactory.decodeStream(assetFile)); //将assets目录下的图片给image            }        });

 

3.assets中的文件列表

 

 

 

 

 

转载地址:https://liuyan.blog.csdn.net/article/details/80010458 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Bitmap.creatBirmap()的简单使用
下一篇:ContentProvider简单使用

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2024年04月06日 06时25分59秒