简体   繁体   English

循环不起作用,为什么会这样?

[英]loop is not working, why is this the case?

I am having trouble understanding this java code. 我在理解此Java代码时遇到了麻烦。 I want the image to twinkle a couple of times, with some delay. 我希望图像闪烁几次,但要延迟一些时间。 The image twinkle once and thats it. 图像一闪而过。 Can someone give me an explanation would be great! 有人可以给我一个解释会很棒!

private void RunAnimations(int[]melodiTakten) { 

    for (int i = 0; i < 4; i++) {  

        ImageView markeringspilen = (ImageView) findViewById(R.id.markeringspil);
        markeringspilen.setVisibility(View.VISIBLE);
        markeringspilen.postDelayed(new Runnable() {
            public void run() {
                ImageView markeringspilen = (ImageView) findViewById(R.id.markeringspil);

                markeringspilen.setVisibility(View.INVISIBLE);
            }
        }, 2000);

    } 

If I understand your idea right, your implementation is wrong in that it sets delayed actions to take place all at the same time. 如果我理解您的想法是正确的,则您的实现是错误的,因为它会将延迟的操作设置为同时发生。 You can space them out like this: 您可以像这样将它们隔开:

for (int i = 0; i < 4; i++) {
    markeringspilen.postDelayed(new Runnable() {
        public void run() {
            ImageView markeringspilen = (ImageView) findViewById(R.id.markeringspil);
            markeringspilen.setVisibility(View.VISIBLE);
        }
    }, 4000*i);
    markeringspilen.postDelayed(new Runnable() {
        public void run() {
            ImageView markeringspilen = (ImageView) findViewById(R.id.markeringspil);
            markeringspilen.setVisibility(View.INVISIBLE);
        }
    }, 4000*i+2000);
}

This loop sets up eight delayed visibility changes - a group of four pairs of set visible at 4000*i followed by set invisible at 4000*i+2000 . 此循环设置了八个延迟的可见性更改-一组四对设置在4000*i可见,然后在4000*i+2000不可见。

the loop is executed, but it's executed very fast and you can't see it. 循环已执行,但执行速度非常快,您看不到它。 You should put some delay in the loop, not only in the runnable. 您应该在循环中放置一些延迟,而不仅是在可运行循环中。

That's because you call setVisibility(View.VISIBLE) four times in a row and then, after a 2s delay, four times setVisibility(View.INVISIBLE) . 那是因为你调用setVisibility(View.VISIBLE)四次连续,然后,一个2秒的延迟后,四次setVisibility(View.INVISIBLE)

What you need to do is add eight runnables with ever increasing delays that in turn toggle the visibility. 您需要做的是添加八个可运行的对象,这些对象的延迟不断增加,从而切换可见性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM