How to move button left or right programmatically in android

I want to animate a button by getting its coordinates, and then increasing or decreasing them one at a time so that the button can go left and then go right.

+5
source share
3 answers

Use TranslateAnimation:

TranslateAnimation animation = new TranslateAnimation(start_x, start_y, end_x, end_y);
animation.setDuration(1000); // duartion in ms
animation.setFillAfter(false);
button.startAnimation(animation);

I'm not sure how you can get its position, button.getTop () and button.getLeft () can work ...

+4
source

Not sure if this will help you, but I was struck by the same problem, I was able to do it using these methods, setTranslationX (float) setTranslationY (float)

you can use it like that

Button button = (button) findViewById(your id); 
button.setTranslationX(a float value);

, http://developer.android.com/reference/android/view/View.html#attr_android:translationX

+3
   Solution for those who are looking for left to right animation)

            TranslateAnimation animation = new TranslateAnimation(0.0f, 0.0f, 0.0f, 1500.0f); // new TranslateAnimation (float fromXDelta,float toXDelta, float fromYDelta, float toYDelta)

               animation.setDuration(1500); // animation duration
                animation.setRepeatCount(1); // animation repeat count
            animation.setFillAfter(false);
                your_view .startAnimation(animation);//your_view for mine is imageView     


Solution for those who are looking for repeated animation(for eg. left to right and right to left)

            TranslateAnimation animation = new TranslateAnimation(0.0f, 0.0f, 0.0f, 1500.0f); // new TranslateAnimation (float fromXDelta,float toXDelta, float fromYDelta, float toYDelta)
                animation.setDuration(1500); // animation duration
                animation.setRepeatCount(4); // animation repeat count
                animation.setRepeatMode(2); // repeat animation (left to right, right to left)

                animation.setFillAfter(true);
                your_view .startAnimation(animation);//your_view for mine is imageView 
0
source

All Articles