我通過添加一些邏輯連接到母體片段解決了這個檢測,當它是被隱藏或顯示,並明確禁用或啓用其子中的動畫。
@Override
public void onPause() {
super.onPause();
// If this fragment is being closed/replaced then disable animations
// in child fragments. Otherwise we get very nasty visual effects
// with the parent and child animations running simultaneously
ChildFragment f = (ChildFragment) getChildFragmentManager()
.findFragmentByTag(FRAGMENT_CHILD);
if (f != null) {
f.disableAnimations();
}
}
@Override
public void onResume() {
super.onResume();
// if this fragment is being opened then re-enable animations
// in child fragments
ChildFragment f = (ChildFragment) getChildFragmentManager()
.findFragmentByTag(FRAGMENT_CHILD);
if (f != null) {
f.enableAnimations();
}
}
在子片段中,我們需要實現這些方法來啓用/禁用動畫。我們通過重寫onCreateAnimation()
並在動畫應該被禁用的情況下使用靜態動畫(R.anim.hold
)來實現。
private boolean mDisableAnimations;
void disableAnimations() {
mDisableAnimations = true;
}
void enableAnimations() {
mDisableAnimations = false;
}
@Override
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
if (mDisableAnimations) {
return AnimationUtils.loadAnimation(getActivity(), R.anim.hold);
}
return super.onCreateAnimation(transit, enter, nextAnim);
}
靜態動畫定義res/anim/hold.xml
爲:
<?xml version="1.0" encoding="utf-8"?>
<translate
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0"
android:toXDelta="0"
android:duration="2000" />
你試過保持你來自哪個活動或片段,並相應地設置您的fragmenttransaction的價值?像'ft.setCustomAnimations(FragmentTransaction.TRANSIT_NONE,FragmentTransaction.TRANSIT_NONE);'當你不需要任何轉換時。我不確定你在哪裏指定你的FragmentTransaction,所以我不知道這是否適合你。 – SvenT23