Johan S
Johan S

Reputation: 3591

Changing button background dynamically in thread in Android

I'm developing my first app for Android and its supposed to be a game. Everything is fine but there's one thing I just can't wrap my head around.

In my game's "main" activity (not the first activity which starts when the app starts) I want to have a method which starts a thread which changes a buttons background color/image (go with color because I haven't made any images just yet) for one second then turns it back. I wan't the method to also have an integer parameter which makes it perform this n times. I want to be able to call like changeButtons(5); and it turns button x background blue for 1 second then waits 1 second five times.

So practically I'm trying to make a "main" thread which runs during the game and inside that thread I'm going to run this method whenever certain conditions are true (a thread which calls a thread).

So I have 2 questions. The first one is "Is this possible? " and If so can someone show me how to do it (not all of it of course but help me get started at least)? Especially I want to know if I can change a buttons background color in a thread and if so can someone show me how to write/get me started that thread?

The second question is a follow-up, if you can do this, can you have a like a boolean b which turns to true if someone presses a button and the thread can "notice" that change? For example, if the thread is running and Obama presses button x and b turns "true" in the method OnClick(View v) can I, inside my main thead have an if(b == true){Obama.moon();} and Obama will moon?

Upvotes: 0

Views: 1624

Answers (1)

Patrick
Patrick

Reputation: 17973

Sure you can.

In android you can use the Handler class (example available) to post actions to the event queue. You can do something like this:

final Handler handler = new Handler();
final Runnable updateRunner = new Runnable() {
    public void run() {
        // we are now in the event handling so to speak,
        // so go ahead and update gui, set color of button for instance
    }
};
new Thread(new Runnable() {
    public void run() {
       while (condition) {
           SystemClock.sleep(1000);
           handler.post(updateRunner);
       }
   }
}).start();

This will trigger the run in updateRunner each second.


Regarding your follow up, it can be done as well (of course :) ). You can for instance implement an observable pattern to the class that handles the button x. When pressed, notify the observers with something like observers.updateChange(b) where you previously had a thatClassOverThere.registerObserver(this) in your main thread.

Upvotes: 4

Related Questions