javaandroidandroid-studioandroid-handlerandroid-handlerthread

UI changes in a thread in android


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

Solution

  • 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.