user3828737 user3828737 - 2 months ago 7
Android Question

Change Layout Background in Thread

I want to change the background color of the thread I use in another class. But unfortunately "only the original thread that created a view hierarchy can touch its views" I get an error.

I would be glad if you could help.

private class thread implements Runnable{

@Override
public void run() {

while (!change_background) {

background.setBackgroundColor(Color.parseColor("#ffffff"));

try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}

background.setBackgroundColor(Color.parseColor("#000000"));

}
}

Answer

Yeah this is right that only main ui can touch its view. But there is a nice workaround for that. Even if you are on another Thread you can call main Thread using runOnUiThread.

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        //write UI related code in here
        background.setBackgroundColor(Color.parseColor("#000000"));
    }
}