Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading