Android Fragment元素共享打开页面有动画,返回没有

Android Fragment元素共享,打开页面时有切换动画,返回时没有切换动画。

共享元素设置

A页面

public class FragmentA extends Fragment {
    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        ...
        ImageView itemImageView = view.findViewById(R.id.item_image);
        //配置元素共享,可在xml配置,必须保持页面唯一性
        ViewCompat.setTransitionName(itemImageView, “item_image”);
    }

    public void showB() {
        ...
        Fragment fragment = new FragmentB();
        getSupportFragmentManager().beginTransaction()
            .setCustomAnimations(...)
            .addSharedElement(itemImageView, “hero_image”)//配置元素共享
            .replace(R.id.fragment_container, fragment)
            .addToBackStack(null)
            .commit();
    }
}

B页面

public class FragmentB extends Fragment {
    @Override
    public View onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Transition transition = TransitionInflater.from(requireContext())
            .inflateTransition(R.transition.shared_image);
        setSharedElementEnterTransition(transition);
    }
}

根据官方文档说明,设置了打开动画,返回默认使用打开设置的那个动画

By default, the shared element enter transition is also used as the return transition for shared elements. The return transition determines how shared elements transition back to the previous fragment when the fragment transaction is popped off the back stack. If you'd like to specify a different return transition, you can do so using Fragment.setSharedElementReturnTransition() in the fragment's onCreate() method.

解决

找了文档跟源码半天,发现写的代码没问题,最后想想是不是Android兼容库导致的,直接给他降级到正式版本就没问题了
我当时使用的是:

implementation 'androidx.appcompat:appcompat:1.3.0-alpha02'   

修改后:

implementation 'androidx.appcompat:appcompat:1.2.0'

应该是appcompat:1.3.0-alpha02版本有bug

你可能感兴趣的:(Android Fragment元素共享打开页面有动画,返回没有)