在循环中引入图像变化之间的延迟

时间:2016-08-20 13:16:19

标签: android

我试图在for循环中引入图像更改之间的延迟。我尝试了Thread.sleep(1000),但延迟是在图像更改之前引入的,在总睡眠周期结束后,ImageView显示最终图像。我在互联网上尝试了很多解决方案但没有任何效果。

public void start(View view){
    ImageView display = (ImageView)findViewById(R.id.imageView);
    for (int i=0;i<6;i++){
        display.setImageResource(R.drawable.dice1+i);
        Thread.sleep(2000);
    }
}

我需要迭代等待2秒才能查看图像。

3 个答案:

答案 0 :(得分:0)

两个问题。

1)不要睡在主线上。永远。相反,创建一个处理程序并使用postDelayed和一个可以更改图像的Runnable。

2)你不能像这样对资源ID进行数学计算。你不能假设他们只是因为他们在文件中彼此相邻而连续。使用id创建一个数组,并使用索引i处的图像。

答案 1 :(得分:0)

您可以按照要求的图像名称获取图像序列

    private int image = 0;

    private static final int MAX_IMAGES = 10;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 55) {
                image++;
                if (image > MAX_IMAGES) {
                    image = 1;
                }
                imageView.setImageDrawable(getImageByName("dice" + image, TestActivity.this));
                mHandler.sendEmptyMessageDelayed(55, 2000);
            }
        }
    };

    public static Drawable getImageByName(String name, Context context) {
        Resources resources = context.getResources();
        final int resourceId = resources.getIdentifier(name, "drawable",
                context.getPackageName());
        return ContextCompat.getDrawable(context, resourceId);
    }

现在通过调用

启动图像序列
mHandler.sendEmptyMessageDelayed(55, 2000);

您的图片将每2秒更改一次

答案 2 :(得分:0)

我认为倒数计时器可以在这种情况下提供帮助。几天前,我在this TableScan interface提出了类似的问题,我得到了这个答案。我认为这对您可能是一个很好的参考。