How to make slide animation with a fixed screen an

2019-08-19 02:24发布

问题:

I made three xml files for the transition.

enter_from_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromXDelta="0%"
        android:fromYDelta="0%"
        android:toXDelta="0%"
        android:toYDelta="0%" />
</set>

none.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromXDelta="100%"
        android:fromYDelta="0%"
        android:toXDelta="0%"
        android:toYDelta="0%" />
</set>

exit_to_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromXDelta="0%"
        android:fromYDelta="0%"
        android:toXDelta="100%"
        android:toYDelta="0%" />
</set>

However, It just works fine in Activities not in Fragments.

When I click the back button, the backward transition(pop) works fine. But it doesn't work properly when I call the new fragment. It just blinks when the screen changes.

I tried changing the duration to 50 of none.xml. And I see the new screen comes in from the right side. And also tried with 10000. But it just delays the changing time.

I am using navigation component. And I defined like this:

        <action
            android:id="@+id/action_initFragment_to_settingFragment"
            app:destination="@id/settingFragment"
            app:enterAnim="@anim/enter_from_right"
            app:exitAnim="@anim/none"
            app:popExitAnim="@anim/exit_to_right"
            app:popEnterAnim="@anim/none"/>

What's wrong with it? I think this is because of Z index. Is there any way to give Z index attribute?

回答1:

This happened because of the z index. Activities have different depth. However, I guess Fragments have the same depth. So, When A Fragment is switched to B Fragment, They are on the same depth and transition is not shown properly.

The solution is giving Z index to the screen programmatically like below:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ViewCompat.setTranslationZ(view, 1F)
    }

1F in here, it is the index of depth.

The interesting thing is the higher value creates the bigger shadow. If you give 100F, then it creates huge shadow underneath. And I can't see any shadows visibly when the value is 1F.



回答2:

I think you have to use the transition inside the "onAttach" overridden method of the fragment.