如何从代码中使用imageview更新图像



我正在尝试制作一个连续显示图像的应用程序(每秒4或5次(,所以我需要更新ImageView对象中的图像,如果我按下按钮触发功能,它就会工作,每次按下按钮都会显示下一个图像:

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++;
}

但是,如果我试图在同一个父函数中多次调用相同的函数,或者我试图在循环中运行它们,则第一个图像根本不会加载,只有最后一个图像在loopFunc((完成后最终显示:

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...
}
}

简而言之,我需要能够从代码而不是从按钮执行image.setImageBitmap(bMap);,谁知道怎么做?感谢

问题在于计算其他事物的时间。你在里面写了什么延迟函数代码吗?

试试这个。只需制作一个函数,并用一些Thread或Handler调用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毫秒循环一次。

根本原因

因为循环在短时间内运行得太快,所以您看到的第一个图像根本没有显示,只有最后一个图像在loopFunc()完成后才最终显示。

解决方案

若要每秒连续显示一系列图像,则应使用Handler。

public void loopFunc() {
Handler mainHandler = new Handler(Looper.getMainLooper());
int totalImage = 3;
for (int i = 1; i < totalImage; i++) {
int imageIndex = i;
mainHandler.postDelayed(new Runnable() {
@Override
public void run() {
String path = String.format("/storage/emulated/0/Download/%d.bmp", imageIndex);
File imgFile = new File(path);
bMap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
image.setImageBitmap(bMap);
}
}, 1000 / totalImage * imageIndex);
}
}

最新更新