簡體   English   中英

循環不起作用,為什么會這樣?

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

我在理解此Java代碼時遇到了麻煩。 我希望圖像閃爍幾次,但要延遲一些時間。 圖像一閃而過。 有人可以給我一個解釋會很棒!

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);

    } 

如果我理解您的想法是正確的,則您的實現是錯誤的,因為它會將延遲的操作設置為同時發生。 您可以像這樣將它們隔開:

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

此循環設置了八個延遲的可見性更改-一組四對設置在4000*i可見,然后在4000*i+2000不可見。

循環已執行,但執行速度非常快,您看不到它。 您應該在循環中放置一些延遲,而不僅是在可運行循環中。

那是因為你調用setVisibility(View.VISIBLE)四次連續,然后,一個2秒的延遲后,四次setVisibility(View.INVISIBLE)

您需要做的是添加八個可運行的對象,這些對象的延遲不斷增加,從而切換可見性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM