In my main activity I have a button with the text “Play”. I want the text to gradually grow and then gradually diminish in size. This should loop until the button is clicked. This effect should appear like a gentle glow.
So, I have tried using a Thread to accomplish this:
// Play Button Animation Thread
Thread playAnimation = new Thread() {
public void run() {
try {
int textSize = 25;
while (textSize <= 50) {
playBtn.setTextSize(textSize);
textSize += .10;
sleep(100);
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
finally {
}
}
};
Then, I called the thread with:
playAnimation.start();
It isn’t working as I have it, but now I’m thinking there is probably a better way. Any help is appreciated.
There are a couple things wrong with the code you have written:
textSizevariable as anint. Thus, your attempt to increment the value by 0.1 each iteration is futile because the value is cast back to an int after each operation, dropping off the value you just added (i.e. 25 += 0.1 -> 25.1, cast back to an int -> 25…lather, rinse repeat). So the value you are passing tosetTextSize()never actually changes.setTextSize()) from any thread you have created. This can be solved by employing aHandlerto manage the threading for you.If you want the entire button to animate, you can look at the animation framework like others have suggested. However, to automate just the text size, you are on the right path…we just need to tweak your code based on the points I mentioned above:
The
Handleris created on the main thread, and all code inside theRunnableis executed on the main thread…so you may update the UI there.postDelayed()takes care of the wait delays so you don’t really need to create another thread at all. To start your animation, just callanywhere in your code. To stop the animation at any time, simply stop calling
postDelayedafter each iteration.HTH!