Skip to content

Instantly share code, notes, and snippets.

@devunwired
Created May 15, 2014 17:03
Show Gist options
  • Save devunwired/ccc6487a1e3fed9c79e0 to your computer and use it in GitHub Desktop.
Save devunwired/ccc6487a1e3fed9c79e0 to your computer and use it in GitHub Desktop.
Method for animating Android fragment positions during a add/replace/remove transition using custom properties. This method does not require subclassing target views with additional setter methods, but instead requires subclassing the fragment...something you are likely already doing.
/**
* An example of adding these transitions to a Fragment. This simple
* version just applies opposite transitions to any Fragment whether it is
* entering or exiting view. You can also inspect the transit mode parameter
* (i.e. TRANSIT_FRAGMENT_OPEN, TRANSIT_FRAGMENT_CLOSE) in combination to do
* different animations for, say, adding a fragment versus popping the back stack.
*
* Transactions without an explicit transit mode set, in this example, will not
* animate. Allowing the initial fragment add, for example, to simply appear.
*/
public class ExampleFragment extends Fragment implements View.OnClickListener {
/** ...Remaining Fragment Code... */
@Override
public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) {
if (transit == 0) {
return null;
}
//Target will be filled in by the framework
return enter ? ObjectAnimator.ofFloat(null, new XFractionProperty(), 1f, 0f)
: ObjectAnimator.ofFloat(null, new XFractionProperty(), 0f, -1f);
}
}
import android.util.Property;
import android.view.View;
public class XFractionProperty extends Property<View, Float> {
public XFractionProperty() {
super(Float.class, "fractionX");
}
@Override
public Float get(View object) {
final int viewWidth = object.getWidth();
if (viewWidth == 0) {
return 0f;
}
return object.getTranslationX() / viewWidth;
}
@Override
public void set(View object, Float value) {
final int viewWidth = object.getWidth();
//Avoid flickers on entering views until they are measured
float translation = viewWidth > 0 ? viewWidth * value : Float.MAX_VALUE;
object.setTranslationX(translation);
}
}
import android.util.Property;
import android.view.View;
public class YFractionProperty extends Property<View, Float> {
public YFractionProperty() {
super(Float.class, "fractionY");
}
@Override
public Float get(View object) {
final int viewHeight = object.getHeight();
if (viewHeight == 0) {
return 0f;
}
return object.getTranslationY() / viewHeight;
}
@Override
public void set(View object, Float value) {
final int viewHeight = object.getHeight();
//Avoid flickers on entering views until they are measured
float translation = viewHeight > 0 ? viewHeight * value : Float.MAX_VALUE;
object.setTranslationY(translation);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment