简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM