首页 > 解决方案 > How to update images with imageview from code

问题描述

I'm trying to make an app that displays images continuosly (4 or 5 times per second) so i need to update an image held inside a ImageView object, it works if i trigger the functions from a button press, every time i press the button the next image gets displayed:

int i = 0;
public void buttonPressed(View view) {
    ImageView image = (ImageView) findViewById(R.id.imageView5);
    String path = String.format("/storage/emulated/0/Download/%d.bmp", i);
    File imgFile = new File(path);
    bMap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
    image.setImageBitmap(bMap);
    i++;
    }

But if i try to call the same functions more than once in the same parent function or i try to run them in a loop the first images are not loaded at all and only the last is finally displayed after loopFunc() completed:

public void loopFunc() {
ImageView image = (ImageView) findViewById(R.id.imageView5);
 for (i = 1; i < 3; i++) {
    String path = String.format("/storage/emulated/0/Download/%d.bmp", i);
    File imgFile = new File(path);
    bMap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
    image.setImageBitmap(bMap);
    //wait some time or do other things...
    }
}

In few words i need to be able to execute image.setImageBitmap(bMap); from code and not from buttons anyone knows how? thanks

标签: javaandroid

解决方案


尝试这个。只需创建一个函数并使用一些线程或处理程序调用它的 onCreate 方法。

public void imgViwer()
    {
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (i = 1; i < 3; i++) {
                    String path = String.format("/storage/emulated/0/Download/%d.bmp", i);
                    File imgFile = new File(path);
                    bMap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                    image.setImageBitmap(bMap);
}
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

每 200 毫秒后,您的循环就会工作。


推荐阅读