android lollipop - setentertransition() for fragme

2019-06-22 16:10发布

问题:

While replacing fragment, I am using Slide animation available for android lollipop version. It works as expected for this particular replacement, but on pressing back button it first pops back current fragment & then reverse of enter animation (slide out) is executed.

private void replaceContentFrameByFragment(Fragment replaceBy, String replaceByFragmentTag) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Slide slide = new Slide(Gravity.BOTTOM);
            slide.setDuration(1000);
            replaceBy.setEnterTransition(slide);
    }
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.content_frame, replaceBy, replaceByFragmentTag);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commitAllowingStateLoss();
}

So, how to force fragment to pop back only after reverse animation of slide is finished? I noticed that activity has method finishAfterTransition() provided. Is there something similar for frgament?

回答1:

I had the same issue, onReturn from Fragment B -> A, Fragment B seem to be doing an extra slide transition. To get around it, I put in a fade transition for setReturnTransition() of a shorter time than the slide which looks quite good (as it dissolves into previous fragment). The code for this is:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    Slide slideRight = new Slide(Gravity.RIGHT);
    slideRight.setDuration(200);
    fragment.setEnterTransition(slideRight);
    Fade fade = new Fade();
    fade.setDuration(100);
    fragment.setReturnTransition(fade);
}


回答2:

I was having the same issue with roughly the same pattern and was able to get around it by posting my fragments transition:

new Handler().post(new Runnable() {
    @Override
    public void run() {
        page.setEnterTransition(new Slide());
        getFragmentManager()
                .beginTransaction()
                .replace(R.id.root_layout, page, "current")
                .commit();
    }
});

Not sure why this resolves the issue (or if this is the absolute correct solution), but it worked for me.