Fragments Android et animation
-
26-10-2019 - |
Question
Comment devriez-vous mettre en œuvre le genre de glissement qui, par exemple le client Gmail utilise Honeycomb?
Can poignée de TransactionManager
cela automatiquement en ajoutant et supprimant les fragments, il est un peu difficile à tester ce en raison de l'émulateur étant un diaporama:)
La solution
Pour animer la transition entre les fragments, ou pour animer le processus d'affichage ou le masquage d'un fragment d'utiliser le Fragment Manager
pour créer un Fragment Transaction
.
Dans chaque transaction Fragment vous pouvez spécifier et des animations qui seront utilisées pour afficher et masquer respectivement (ou les deux en remplacement est utilisé).
Le code suivant montre comment vous devez remplacer un fragment par un fragment faisant glisser et glisser l'autre à sa place.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
DetailsFragment newFragment = DetailsFragment.newInstance();
ft.replace(R.id.details_fragment_container, newFragment, "detailFragment");
// Start the animated transition.
ft.commit();
Pour obtenir la même chose avec cacher ou montrant un fragment que vous souhaitez simplement appeler ft.show
ou ft.hide
, en passant dans le fragment que vous souhaitez afficher ou masquer respectivement.
Pour référence, les définitions d'animation XML utiliserait la balise objectAnimator
. Un exemple de slide_in_left pourrait ressembler à ceci:
<?xml version="1.0" encoding="utf-8"?>
<set>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:propertyName="x"
android:valueType="floatType"
android:valueFrom="-1280"
android:valueTo="0"
android:duration="500"/>
</set>
Autres conseils
Si vous ne devez pas utiliser la bibliothèque de support alors jetez un oeil à réponse Roman.
Mais si vous voulez utiliser la bibliothèque Support vous devez utiliser l'ancien cadre d'animation tel que décrit ci-dessous.
Après avoir consulté et Reto réponses de blindstuff j'ai obtenu le travail de code suivant.
Les fragments apparaissent glissement de la droite et coulissant vers la gauche moment de retour est actionné.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
CustomFragment newCustomFragment = CustomFragment.newInstance();
transaction.replace(R.id.fragment_container, newCustomFragment );
transaction.addToBackStack(null);
transaction.commit();
L'ordre est important. Cela signifie que vous devez appeler setCustomAnimations()
avant replace()
ou l'animation ne prendront effet!
Suivant ces fichiers doivent être placés à l'intérieur du res / anim dossier.
enter.xml :
<?xml version="1.0" encoding="utf-8"?>
<set>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="100%"
android:toXDelta="0"
android:interpolator="@android:anim/decelerate_interpolator"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
exit.xml :
<set>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0"
android:toXDelta="-100%"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
pop_enter.xml :
<set>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="-100%"
android:toXDelta="0"
android:interpolator="@android:anim/decelerate_interpolator"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
pop_exit.xml :
<?xml version="1.0" encoding="utf-8"?>
<set>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0"
android:toXDelta="100%"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
La durée des animations peut être modifiée à l'une des valeurs par défaut comme @android:integer/config_shortAnimTime
ou tout autre numéro.
Notez que si entre le remplacement fragment d'un changement de configuration se produit (par exemple rotation) l'action de retour n'est pas animé. Ceci est un bogue documenté qui existe encore dans le rev 20 la bibliothèque de soutien.
Je suggère fortement que vous utilisez ce lieu de créer le fichier d'animation, car il est une solution beaucoup mieux. Android Studio fournit déjà par défaut animation
vous pouvez utiliser sans créer de fichier XML nouveau. Les noms des animations sont android.R.anim.slide_in_left et android.R.anim.slide_out_right et vous pouvez les utiliser comme suit:
fragmentTransaction.setCustomAnimations (android.R.anim.slide_in_left, android.R.anim.slide_out_right);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
fragmentManager.addOnBackStackChangedListener(this);
fragmentTransaction.replace(R.id.frame, firstFragment, "h");
fragmentTransaction.addToBackStack("h");
fragmentTransaction.commit();
Sortie:
Mon modifié la bibliothèque de soutien supports utilisant à la fois des animations de vue (par exemple <translate>, <rotate>
) et Animateurs d'objets (c.-à- <objectAnimator>
) pour les transitions Fragment. Il est mis en œuvre avec NineOldAndroids . Reportez-vous à ma documentation sur GitHub pour plus de détails.
Je résous ce la manière ci-dessous
Animation anim = AnimationUtils.loadAnimation(this, R.anim.slide);
fg.startAnimation(anim);
this.fg.setVisibility(View.VISIBLE); //fg is a View object indicate fragment
Pour ma part, j'ai besoin de la vue DirAction:
-> swipe de droite
out -> swipe à gauche
fonctionne ici pour moi le code:
slide_in_right.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="50%p" android:toXDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
slide_out_left.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="-50%p"
android:duration="@android:integer/config_mediumAnimTime"/>
<alpha android:fromAlpha="1.0" android:toAlpha="0.0"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
Code de transaction:
inline fun FragmentActivity.setContentFragment(
containerViewId: Int,
backStack: Boolean = false,
isAnimate: Boolean = false,
f: () -> Fragment
): Fragment? {
val manager = supportFragmentManager
return f().apply {
manager.beginTransaction().let {
if (isAnimate)
it.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
if (backStack) {
it.replace(containerViewId, this, "Fr").addToBackStack("Fr").commit()
} else {
it.replace(containerViewId, this, "Fr").commit()
}
}
}
}