0

I'm writing an android application that require me to hold the foreground of an Image Button for a second before changing it again. so I have written the code below (it worked on changing the colors of the text on two buttons in some other project) and I know that the problem is that I'm changing UI element in a non-main thread and im aware that i cant use "runOnUiThread" method but cant find a way to do so in my current function so please if someone can help me its appreciated.

public void waitTime(ImageButton imageButton1, ImageButton imageButton2) {
    HandlerThread handlerThread = new HandlerThread("showText");
    handlerThread.start();
    Handler handler = new Handler(handlerThread.getLooper());
    Runnable runnable = () -> {
        imageButton1.setForeground(AppCompatResources.getDrawable(this, R.color.teal_200));
        imageButton2.setForeground(AppCompatResources.getDrawable(this, R.color.teal_200));
    };
    handler.postDelayed(runnable, 1000);
}
Sergio
  • 27,326
  • 8
  • 128
  • 149
moustafa
  • 27
  • 5

1 Answers1

0

You can use View's postDelayed method:

Runnable runnable = () -> {
        imageButton1.setForeground(AppCompatResources.getDrawable(this, R.color.teal_200));
        imageButton2.setForeground(AppCompatResources.getDrawable(this, R.color.teal_200));
    };
imageButton1.postDelayed(runnable, 1000);

It will updated UI in Main Thread.

Sergio
  • 27,326
  • 8
  • 128
  • 149
  • it worked amazingly but can i just get a brief explanation about the difference ? – moustafa Jan 18 '22 at 21:19
  • In your code you are calling `handler.postDelayed` on a Handler which attached to background thread, you can't update UI from Runnable passed to it. Using `View.postDelayed` method you can update UI after some time in the future, because runnable will be run on the user interface thread. So basically what you want is already in the SDK, no need to use additional Handlers and HandlerThread. – Sergio Jan 18 '22 at 21:23
  • oh great thanks man !! – moustafa Jan 18 '22 at 21:25