Search code examples
androidmultithreadingbuttonvisibleinvisible

Toggle button visibility in for-loop


It must work, but is not working. When i start the app i see a button. Now i want that the button is visible and invisible.

for (k = 0; k < abc.length; ++k) {
try {

    if (k%2 != 0) {
        button.setVisibility(View.VISIBLE);
    } else {
        button.setVisibility(View.GONE);
    }

    Thread.sleep(sleepMilliseconds);

} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

Or is the for loop so fast, that the android can't show it? Nothing happens. I see the button.

I have a Thread.sleep(). Sleep Milliseconds is e.g. 100, 300 -> random. Also it can't be so fast.


Solution

  • I have a Thread.sleep(). Sleep Milliseconds is e.g. 100, 300 -> random. Also it can't be so fast.

    You're sleeping in the UI thread. That's the problem. You're not letting the rest of the UI thread do its work.

    If you want to periodically update the UI, you should be using a timer instead, or possibly call Handler.postDelayed at the end of each update, to schedule the next update. Alternatively, use the Property Animation system.