Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

android - How to animate a View's translation

At the first click of a button, I want to slide a View along the x-axis (by 200 pixels to the right let's say). And on the second press of the button, I want to slide the View back along the x-axis to its original position.

The View.setTranslationX(float) method jumps the View to the target horizontal locations with calls myView.setTranslationX(200); and myView.setTranslationX(0); respectively. Anyone know how I can slide the View to the target horizontal locations instead?

Note 1: A TranslateAnimation is no good since it doesn't actually move the View but only presents the illusion of it moving.

Note 2: I didn't realise at the time of posing the question that the setTranslationX(float) and setTranslationY(float) methods were introduced as of API Level 11. If you're targeting Honeycomb (API Level 11) upwards, then Gautam K's answer will suffice. Otherwise, see my answer for a suggested solution.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try looking into ObjectAnimator and its super class Value Animator

you can do something like this ObjectAnimator anim = ObjectAnimator.ofFloat(this, "translationX", 0,200); and then anim.start();

Use a boolean value and toggle it with 200,0 in the object animator to slide back

PS: you can use setDuration method to set how long the animation should take to complete

Edit :

Try looking at the support library which provides backward compatibility.

Edit

As @AdilHussain pointed out there is a library called nineoldandroids which can be used for the same purpose on older androids.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...