Reputation: 925
I'd like to translate view with ObjectAnimator twice, but the "X" position gets back to starting position after pressing the button again, how can i make it continue, and move further right in this case?
final ObjectAnimator animation = ObjectAnimator.ofFloat(button, "translationX", 100f);
animation.setDuration(2000);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
animation.start();
}
});
Upvotes: 1
Views: 1910
Reputation: 54204
The reason your button jumps back to its starting position is covered in the documentation for the ofFloat()
method:
A single value implies that that value is the one being animated to, in which case the start value will be derived from the property being animated and the target object when
start()
is called for the first time.
Because you're reusing the same ObjectAnimator
instance every time, the translationX
property is animated from its original (0) to the passed in argument (100) every time.
However, you can't just change it to create a new ObjectAnimator
and have that solve everything. Let's say you changed your code to this:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final ObjectAnimator animation = ObjectAnimator.ofFloat(button, "translationX", 100f);
animation.setDuration(2000);
animation.start();
}
});
That would change what happens, but still not give you what you want. Now the button would slide from 0 to 100 the first time, but would remain stationary every time after that.
Why?
Because after the first animation, the translationX
property is 100. So now you're animating between 100 and 100 (instead of 0 and 100)... which doesn't do anything.
The solution is to animate from the view's current translationX
to the current value + 100. And to do that every time, instead of re-using the same ObjectAnimator
over and over.
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
float end = button.getTranslationX() + 100;
ObjectAnimator animation = ObjectAnimator.ofFloat(button, "translationX", end);
animation.setDuration(2000);
animation.start();
}
});
Upvotes: 5
Reputation: 104
button.animate().translationX(button.translationX + 100f).setDuration(1000).start()
Works like a charm
Upvotes: 1