how to setCustomAnimations for FragmentTransaction on this code

若如初见. 提交于 2020-01-31 13:09:49

问题


i have 5 fragments and I use the following code to setCustomAnimations for FragmentTransaction:

FragmentTransaction trans = getFragmentManager().beginTransaction();
trans.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);

but how to setCustomAnimations for this one:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK ) {
        if (getSupportFragmentManager().getBackStackEntryCount() == 0)
        {
            this.finish();
            return false;
        }
        else
        {
            getSupportFragmentManager().popBackStack();
            return false;
        }



    }

    return super.onKeyDown(keyCode, event);
}

回答1:


There is a second setCustomAnimations method (here's the support library method) that has two extra IDs present for the inclusion of the animation to be used when you pop the back stack. Pass the animation IDs you wish to occur when the back stack is popped (transaction is reversed) in the last to spots.

FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(android.R.anim.slide_in_left, 
                                android.R.anim.slide_out_right,
                                ANIMATION_ID_FOR_ENTERING_VIEW,
                                ANIMATION_ID_FOR_EXITING_VIEW);

Then when you call

getFragmentManager().popBackStack();

The animations will play, the third animation passed to that method will play for the view that you originally removed, and the fourth will play for the view that was visible and is being removed. From the current animations you have for the initial transaction, I would guess you want to use android.R.anim.slide_in_right and android.R.anim.slide_out_left for the back stack animations (see below):

transaction.setCustomAnimations(android.R.anim.slide_in_left,
                                android.R.anim.slide_out_right,
                                android.R.anim.slide_in_right,
                                android.R.anim.slide_out_left);

You only have to call setCustomAnimations when initially adding the fragment to the stack (just like you are doing now, simply add the extra animation IDs), the back stack will remember the animations you set and will automatically play them when you pop back.

NOTE: This method is only available in API 13 and above unless you are using the support v4 jar, which it looks like you are (as you are using getSupportFragmentManager() instead of the regular method).



来源:https://stackoverflow.com/questions/25013689/how-to-setcustomanimations-for-fragmenttransaction-on-this-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!