How to animate button in android?

omega picture omega · Aug 14, 2013 · Viewed 106.3k times · Source

I am making an android app, and I have a button which leads to a messaging place. On the activity with the button, I check if there is any unread messages, and if so I want to do something to the button to let the user know that there is something unread.

I was thinking of having the button sorta vibrate horizontally like 3 shakes every 2 or 3 seconds.

I know how to run a thread in the background which does something every x milliseconds. But what I don't know what to do is shake it horizontally 3 times.

Can anyone help with this?

I was thinking of using the sin function, for the animation, I can use output from a sin function to get values that go up and down, which I can set the horizontal position of the button... But this seems too extreme, is there a better way?

Answer

user2323030 picture user2323030 · Feb 26, 2014

I can't comment on @omega's comment because I don't have enough reputation but the answer to that question should be something like:

shake.xml

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="100"          <!-- how long the animation lasts -->
    android:fromDegrees="-5"        <!-- how far to swing left -->
    android:pivotX="50%"            <!-- pivot from horizontal center -->
    android:pivotY="50%"            <!-- pivot from vertical center -->
    android:repeatCount="10"        <!-- how many times to swing back and forth -->
    android:repeatMode="reverse"    <!-- to make the animation go the other way -->
    android:toDegrees="5" />        <!-- how far to swing right -->

Class.java

Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
view.startAnimation(shake);

This is just one way of doing what you want, there may be better methods out there.