View Animation
Surprisingly enough, there does not seem to be a way to specify a 300dp translate animation in XML. The translate animation XML syntax accepts three different distance specifications:
- Absolute pixels relative to normal position (e.g.
android:toYDelta="10"
) - Percentage relative to element width/height (e.g.
android:toYDelta="10%"
) - Percentage relative to parent width/height (e.g.
android:toYDelta="10%p"
)
You are also restrained to the same specifications when you create a TranslateAnimation
via Java. However, in Java you can calculate the equivalent absolute pixel value (for a given device) and supply that as your pixel translate distance.
To get 300dp, you can either define a dimen value of 300dp in XML, or simply perform the calculation in code.
Inside dimens.xml
:
<dimen name="distance">300dp</dimen>
Inside your Activity/Fragment/etc:
float distance = getResources().getDimensionPixelSize(R.dimen.distance);
OR
Inside your Activity/Fragment/etc:
float distance = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 300,
getResources().getDisplayMetrics()
);
Then all you need to do is use that distance when creating your TranslateAnimation
:
TranslateAnimation animation = new TranslateAnimation(
Animation.ABSOLUTE, 0,
Animation.ABSOLUTE, 0,
Animation.ABSOLUTE, 0,
Animation.ABSOLUTE, distance
);
Property Animation
If you are targeting Android 3.0 and above, you can use the new Property Animation framework to express the same animation more elegantly:
view.animate().translationY(distance).setDuration(...).start();
If you are still targeting Android 2.x, you can use NineOldAndroids to get backwards compatible animation syntax. It will automatically use the new property animations for devices that support it.
ViewPropertyAnimator.animate(view).translationY(distance).setDuration(...).start();