Skip to content

Instantly share code, notes, and snippets.

@bherbst
Last active November 4, 2015 16:39
Show Gist options
  • Save bherbst/82b0475fc9b525ec7c5d to your computer and use it in GitHub Desktop.
Save bherbst/82b0475fc9b525ec7c5d to your computer and use it in GitHub Desktop.
Picasso delay for Fragment transitions
public class PicassoFragment extends Fragment {
private static final String KEY_WILL_ANIMATE_IMAGE = "keyWillAnimateImage";
private boolean willAnimateImage;
/**
* Get a new PicassoFragment instance
* @param wilAnimateImage True if the image will animate in during the tragment transaction
*/
public static PicassoFragment newInstance(boolean willAnimateImage) {
PicassoFragment frag = new PicassoFragment();
Bundle args = new Bundle();
args.putBoolean(KEY_WILL_ANIMATE_IMAGE, willAnimateImage);
frag.setArguments(args);
return frag;
}
@Override
public void onCreate(Bundle savedInstanceState) {
willAnimateImage = false;
if (getArguments() != null) {
willAnimateImage = getArguments().getBoolean(KEY_WILL_ANIMATE_IMAGE, false);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void setSharedElementEnterTransition(Object transition) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
&& transition != null
&& transition instanceof Transition) {
((Transition) transition).addListener(new Transition.TransitionListener() {
@Override
public void onTransitionStart(Transition transition) {}
@Override
public void onTransitionEnd(Transition transition) {
onEnterTransitionFinished();
}
@Override
public void onTransitionCancel(Transition transition) {
onEnterTransitionFinished();
}
@Override
public void onTransitionPause(Transition transition) {}
@Override
public void onTransitionResume(Transition transition) {}
});
}
super.setSharedElementEnterTransition(transition);
}
/**
* Called when the enter transition is finished so we can use Picasso to load the correct image.
*/
private void onEnterTransitionFinished() {
willAnimateBadge = false;
if (isAdded() && isVisible()) {
RequestCreator picassoRequest = Picasso.with(getActivity())
.load("http://example.com/image.jpg");
if (imageView.getDrawable() != null) {
// If we already have an image, use it as the placeholder to prevent a flicker
// when the new image is fetched
picassoRequest.placeholder(imageView.getDrawable());
}
picassoRequest.into(imageView);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment