问题
I have an Activity (A) that creates a DialogFragment. In that DialogFragment, I have a button which creates a new Activity (B). When I finish Activity B, it displays the DialogFragment from Activity A and it reuses that custom animation I set. How do I prevent my DialogFragment from reusing that animation when returning to Activity A?
This answer works for some devices, however it freezes the entire window on some (hence the check version)
@Override
public void onStop() {
super.onStop();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
getDialog().getWindow().setWindowAnimations(-1);
}
}
https://stackoverflow.com/a/64454784/11110509
This is how I am creating my custom DialogFragment enter/exit animation:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.getWindow().getAttributes().windowAnimations = R.style.FragmentDialogAnim;
return dialog;
}
<style name="FragmentDialogAnim">
<item name="android:windowEnterAnimation">@anim/loginactivity_left_to_right</item>
<item name="android:windowExitAnimation">@anim/loginactivity_right_to_left</item>
</style>
loginactivity_left_to_right:
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate android:fromXDelta="-100%" android:toXDelta="0%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="700"/>
</set>
loginactivity_right_to_left:
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate
android:fromXDelta="0%" android:toXDelta="-100%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="700" />
</set>
Here's the code for creating the DialogFragment:
https://pastebin.com/k1c6nz3p
回答1:
You should disable the animation in onPause() method of your DialogFragment instead of onStop() method. Just remove all the lines of code you currently have in onStop() method and add onPause() with the below lines of code:
@Override
public void onPause() {
super.onPause();
if(getDialog()!=null)
getDialog().getWindow().setWindowAnimations(-1);
}
By doing it in onPause() method you are disable all window animations without also to freeze any touch events.
回答2:
Recycling Views can always be problematic especially if you intend it to be slightly different in each scenario.
I would recommend that either you stop recycling this Dialog and instead create a specific Dialog for each of your different cases, or that you simply pass a flag into your Dialog defining what/when to use the animations.
来源:https://stackoverflow.com/questions/65161454/returning-to-dialogfragment-from-another-activity-reuses-my-enter-animation