带阴影的淡出动画

Fade out animation with shade

我正在使用淡出动画退出片段,效果很好。我现在要做的是将现有片段的背景颜色设置为灰色,就像 AlertDialog 的动画一样。这是我的动画文件:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <scale
         android:duration="300"
         android:fromXScale="1.0"
         android:fromYScale="1.0"
         android:pivotX="50%"
         android:pivotY="50%"
         android:toXScale="0.0"
         android:toYScale="0.0" />

    <alpha
         android:duration="300"
         android:fromAlpha="1.0"
         android:interpolator="@android:anim/decelerate_interpolator"
         android:toAlpha="0.0" />

</set>

是否可以更改此文件中的背景颜色,或者我需要在其他地方进行更改?

此文件名为 center_pop_up_exit,当用户单击监听器的按钮时,我正在使用它:

View.OnClickListener noAccountHandler = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        SignUpFragment signUpFragment = new SignUpFragment();
        FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
        fragmentTransaction.setCustomAnimations(R.anim.slide_left_enter, R.anim.center_pop_up_exit, 0, R.anim.center_pop_up_exit);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(R.id.log_in_fragment_container, signUpFragment, "SignUpFragment");
        fragmentTransaction.commit();
    }
};

我还没有找到在动画中做到这一点的方法xml。但是,我设法通过使用 TransitionDrawable 获得了我想要的效果。所以首先,我创建了一个 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- The drawables used here can be solid colors, gradients, shapes, images, etc. -->
    <item android:drawable="@color/transparent" />
    <item android:drawable="@color/transp_black" />
</transition>

之后我需要将这个文件设置为我想要阴影的视图的背景(在我的例子中,这是我的片段的容器):

<FrameLayout
    android:id="@+id/shade"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/transition_drawable"/>

然后我获取视图,获取视图的背景并进行转换:

shadeLayout = postMeasurementsFragment.getView().findViewById(R.id.shade);
TransitionDrawable transitionDrawable = (TransitionDrawable)shadeLayout.getBackground();
transitionDrawable.startTransition(200);

最后,在触发转换后我可以进行片段交易:

Fragment fragment = new PostMeasurementFragment();
FragmentTransaction fragmentTransaction = ((PostActivity)context).getSupportFragmentManager().beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.setCustomAnimations(R.anim.slide_up_enter,0,0,R.anim.slide_down_exit);
    fragmentTransaction.add(R.id.modal_measurement_container, fragment, "PostMeasurementFragment");
    fragmentTransaction.commit();

另外:如果您需要还原该转换,您可以再次获取视图和视图的背景并进行另一个转换:

TransitionDrawable transitionDrawable = (TransitionDrawable)shadeLayout.getBackground();
transitionDrawable.reverseTransition(200);

在我的例子中,我在 popBackStack 之前使用它。就是这样!