Android: Using ObjectAnimator to translate a View with fractional values of the View's dimension
Solution 1:
Actually object animators accept fractional values. But maybe you didn't understand the underlying concept of an objectAnimator or more generally a value animator. A value animator will animate a value related to a property (such as a color, a position on screen (X,Y), an alpha parameter or whatever you want). To create such a property (in your case xFraction and yFraction) you need to build your own getters and setters associated to this property name. Lets say you want to translate a FrameLayout from 0% to 25% of the size of your whole screen. Then you need to build a custom View that wraps the FrameLayout objects and write your getters and setters.
public class SlidingFrameLayout extends FrameLayout
{
private static final String TAG = SlidingFrameLayout.class.getName();
public SlidingFrameLayout(Context context) {
super(context);
}
public SlidingFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public float getXFraction()
{
int width = getWindowManager().getDefaultDisplay().getWidth();
return (width == 0) ? 0 : getX() / (float) width;
}
public void setXFraction(float xFraction) {
int width = getWindowManager().getDefaultDisplay().getWidth();
setX((width > 0) ? (xFraction * width) : 0);
}
}
Then You can use the xml way to declare the object animator putting xFraction under the property xml attribute and inflate it with a AnimatorInflater
<?xml version="1.0" encoding="utf-8"?>
<objectAnimator
xmlns:android="http://schemas.android.com/apk/res/android"
android:propertyName="xFraction"
android:valueType="floatType"
android:valueFrom="0"
android:valueTo="0.25"
android:duration="500"/>
or you can just use the java line code
ObjectAnimator oa = ObjectAnimator.ofFloat(menuFragmentContainer, "xFraction", 0, 0.25f);
Hope it helps you!
Olivier,
Solution 2:
Android SDK implementation of FragmentTransaction
expects an Animator
while, for some obscure reason, the support library implementation expects an Animation
, if you use Fragment implementation from support library your translate animation will work
Solution 3:
Here is an important gotcha for those who are trying to create view animations like translate
and scale
.
Property animations are located in a directory named "animator": res/animator/filename.xml
BUT, view animations must be put in a directory simply called "anim":
res/anim/filename.xml
I first put my view animation in an "animator" folder, and was confused about Android Studio complaining about how translate was not a valid element. So, NO, view animations are not deprecated. They just have their own location for some confusing reason.