我浏览了 stackoverflow 和所有类似的答案 - 但发现它们没有用。
谁能指出为什么这不起作用?它应该很简单:每 6 秒更新一次图像(将每 3 分钟更新一次,但为了测试我将其设置为 6 秒)。
代码的作用是 - 逐步检查 4 张图像中的每一张,但不更改图像。然而,当它到达最后一张图片时 - 它确实改变了它(??)。
问题:
- 这有什么问题吗?
- 为什么它只更新最后一张图片?
- 如果我在代码开始时只向处理程序发送一个“post”而不是“postDelayed”- 平板电脑将保持黑屏。为什么我必须延迟启动代码才能使其工作?
int currentIndex = 0;
bool 开始=假;
图片查看描述图片;
私有(private) Runnable timerRunnable;
长启动时间= 0;
私有(private)处理程序处理程序;
int[] pictureIds = new int[]{R.drawable.hang, R.drawable.dog, R.drawable.coffee, R.drawable.about};
@覆盖
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pictureDescription = new ArrayList();
handler = new Handler(Looper.getMainLooper());
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
查看 v = inflater.inflate(R.layout.fragment_picture_test, container, false);
descriptionImage = (ImageView) v.findViewById(R.id.iv_picture);
返回 v;
}
@覆盖
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
开始();
}
私有(private)无效开始(){
开始=真;
startTime = System.currentTimeMillis();
加载图像();
timerRunnable = new Runnable() {
@覆盖
公共(public)无效运行(){
而(开始){
长时间 = System.currentTimeMillis() - 开始时间;
float 分钟数 = ( float ) 时间/(60 * 1000);
如果(分钟 >= 0.1f){
startTime = System.currentTimeMillis();
如果(currentIndex < pictureIds.length){
当前索引++;
加载图像();
}
}
}
}
};
handler.postDelayed(timerRunnable, 1000);
}
私有(private)无效loadImage(){
getActivity().runOnUiThread(new Runnable() {
@覆盖
公共(public)无效运行(){
如果(currentIndex < pictureIds.length){
descriptionImage.setImageResource(pictureIds[currentIndex]);
} 别的 {
开始=假;//结束
}
}
});
}
谢谢!
编辑:如果我将它发布到 imageview 线程而不是处理程序,则不起作用。
descriptionImage.postDelayed(timerRunnable, 1000);
最佳答案
What's wrong with this?
当 UI 线程忙 (while (start)
) 时,等待您的条件变为真 (if (mins >= 0.1f) {
),它无法处理其余的事情(例如绘图)。
Why would it only update the last image?
因为它只能在if (currentIndex < pictureIds.length) {
时绘制不是真的,start
变为 false,UI 线程终于可以绘制了
If I start the code with just a "post" to the handler instead of a "postDelayed" - the tablet just stays with a black screen. Why do I have to start the code with a delay to make it work?
见第 1 点。
如果你想每 3 秒更改一次图像,你可以继续使用 Handler#postDelayed。例如
start = true;
startTime = System.currentTimeMillis();
loadImage();
timerRunnable = new Runnable() {
@Override
public void run() {
currentIndex = currentIndex++ % pictureIds.length;
loadImage();
handler.postDelayed(this, 3000);
}
};
handler.postDelayed(timerRunnable, 3000);
关于android - 在 Android 线程上更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44506961/