簡體   English   中英

Simon表示按下按鈕后按鈕的顏色不會恢復正常

[英]Simon Says button color won't return to normal after button press

public void flashButton(int color) {
    final ImageView colors = findViewById(R.id.buttonsImage);
    final int newColor = color;

    Handler handler = new Handler();
    final Runnable r = new Runnable() {
        public void run() {
            if(newColor == 1)
                colors.setImageResource(R.drawable.green_activated_png);
            if(newColor == 2)
                colors.setImageResource(R.drawable.yellow_activated_png);
            if(newColor == 3)
                colors.setImageResource(R.drawable.red_activated_png);
            if(newColor == 4)
                colors.setImageResource(R.drawable.blue_activated_png);

            System.out.println("Flashed color: " + newColor);
        }
    };
    handler.postDelayed(r, 1000);

    colors.setImageResource(R.drawable.normal_buttons);
    System.out.println("Returned Color.");
}

使用R.drawable.green_activated_png為每個按鈕更改按鈕顏色。 然后,我用(R.drawable.normal_buttons)將其改回。 我在想我的問題在handler.postDelayed(r,1000)中。 但是在用戶按下正確的顏色后,顏色不會恢復為正常。

您正好相反。按下Button后必須立即更改Button的顏色,並且必須將返回的顏色保留為postDelayed以便在給定時間的延遲后它變為正常顏色。

public void flashButton(int color) {
    final ImageView colors = findViewById(R.id.buttonsImage);
    final int newColor = color;
    if(newColor == 1)
        colors.setImageResource(R.drawable.green_activated_png);
    if(newColor == 2)
        colors.setImageResource(R.drawable.yellow_activated_png);
    if(newColor == 3)
        colors.setImageResource(R.drawable.red_activated_png);
    if(newColor == 4)
        colors.setImageResource(R.drawable.blue_activated_png);
    System.out.println("Flashed color: " + newColor);

    Handler handler = new Handler();
    final Runnable r = new Runnable() {
        public void run() {
            colors.setImageResource(R.drawable.normal_buttons);
            System.out.println("Returned Color.");
        }
    };
    handler.postDelayed(r, 1000);
}

我認為該功能的流程不正確。 因為發布延遲方法在1秒鍾后執行。 在此之前,將執行colors.setImageResource(R.drawable.normal_buttons)方法。 如下更改流程

public void flashButton(int color) {
final ImageView colors = findViewById(R.id.buttonsImage);
final int newColor = color;
        if(newColor == 1)
            colors.setImageResource(R.drawable.green_activated_png);
        if(newColor == 2)
            colors.setImageResource(R.drawable.yellow_activated_png);
        if(newColor == 3)
            colors.setImageResource(R.drawable.red_activated_png);
        if(newColor == 4)
            colors.setImageResource(R.drawable.blue_activated_png);

Handler handler = new Handler();
final Runnable r = new Runnable() {
    public void run() {
        colors.setImageResource(R.drawable.normal_buttons);
    }
};
handler.postDelayed(r, 1000);
}

暫無
暫無

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

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