java - 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
解决方案
尝试这个。只需创建一个函数并使用一些线程或处理程序调用它的 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 毫秒后,您的循环就会工作。
推荐阅读
- r - 安装包“生命周期”时出错(尝试安装 ggplot 3.3.0、R 3.5.3 时)
- windows - 如何将这两个“FOR”循环合二为一?
- java - 通过 cmd 在 Windows 10 上安装 Android SDK 时遇到问题
- intellij-idea - 编译 java 文件时 IDEA IntelliJ 出现“用于编码 UTF-8 的不可映射字符”错误
- javascript - 仅切换 Reactjs 中单击的菜单
- python - 如何从 msg 文件中提取数据并将它们插入(附加)到 csv 文件?
- entity-framework-core - Entity Core 和 SaveChanges 只工作一次
- python-3.x - 如何使用交叉验证和预测标签测试看不见的测试数据?
- android - 如果你想用它来保护整个应用程序(例如银行应用程序),你如何正确配置 local_auth?
- javascript - 检查 HTML 元素是否在视口中