Android - Transition de fragment

Qu'est-ce qu'une transition?

Les transitions d'activité et de fragment dans Lollipop reposent sur une fonctionnalité relativement nouvelle d'Android appelée Transitions. Introduit dans KitKat, le framework de transition fournit une API pratique pour animer entre différents états d'interface utilisateur dans une application. Le cadre est construit autour de deux concepts clés: les scènes et les transitions. Une scène définit un état donné de l'interface utilisateur d'une application, tandis qu'une transition définit le changement animé entre deux scènes.

Lorsqu'une scène change, une transition a deux responsabilités principales -

  • Capturez l'état de chaque vue dans les scènes de début et de fin.
  • Créez un animateur basé sur les différences qui animera les vues d'une scène à l'autre.

Exemple

Cet exemple vous expliquera comment créer votre animation personnalisée avec transition de fragment. Alors, suivons les étapes suivantes pour ressembler à ce que nous avons suivi lors de la création de Hello World Exemple -

Étape La description
1 Vous utiliserez Android Studio pour créer une application Android et la nommerez comme fragmentcustomanimations sous un package com.example.fragmentcustomanimations , avec une activité vide.
2 Modifiez le activity_main.xml, qui a placé à res / layout / activity_main.xml pour ajouter une vue de texte
3 Créez une mise en page appelée fragment_stack.xml.xml sous le répertoire res / layout pour définir votre balise de fragment et votre balise de bouton
4 Créez un dossier, qui est placé à res / et nommez-le comme animation et ajoutez fragment_slide_right_enter.xml fragment_slide_left_exit.xml,, fragment_slide_right_exit.xml et fragment_slide_left_enter.xml
5 Dans MainActivity.java, vous devez ajouter une pile de fragments, un gestionnaire de fragments et onCreateView ()
6 Exécutez l'application pour lancer l'émulateur Android et vérifier le résultat des modifications effectuées dans l'application.

ce qui suit sera le contenu de res.layout / activity_main.xml qu'il contenait TextView

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/text"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:gravity="center_vertical|center_horizontal"
   android:text="@string/hello_world"
   android:textAppearance="?android:attr/textAppearanceMedium" />

Voici le contenu de res/animation/fragment_stack.xmlfichier. il contenait une disposition de cadre et un bouton

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical" >
   
   <fragment
      android:id="@+id/fragment1"
      android:name="com.pavan.listfragmentdemo.MyListFragment"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />

</LinearLayout>

Voici le contenu de res/animation/fragment_slide_left_enter.xmlfichier. il contenait une méthode d'ensemble et un animateur d'objets

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
   <objectAnimator
      android:interpolator="@android:interpolator/decelerate_quint"
      android:valueFrom="100dp" android:valueTo="0dp"
      android:valueType="floatType"
      android:propertyName="translationX"
      android:duration="@android:integer/config_mediumAnimTime" />
   
   <objectAnimator
      android:interpolator="@android:interpolator/decelerate_quint"
      android:valueFrom="0.0" android:valueTo="1.0"
      android:valueType="floatType"
      android:propertyName="alpha"
      android:duration="@android:integer/config_mediumAnimTime" />
</set>

suivant sera le contenu de res/animation/fragment_slide_left_exit.xml file.it contenait des balises d'animation d'ensemble et d'objet.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
   <objectAnimator
      android:interpolator="@android:interpolator/decelerate_quint"
      android:valueFrom="0dp" android:valueTo="-100dp"
      android:valueType="floatType"
      android:propertyName="translationX"
      android:duration="@android:integer/config_mediumAnimTime" />
   
   <objectAnimator
      android:interpolator="@android:interpolator/decelerate_quint"
      android:valueFrom="1.0" android:valueTo="0.0"
      android:valueType="floatType"
      android:propertyName="alpha"
      android:duration="@android:integer/config_mediumAnimTime" />
</set>

Le code suivant sera le contenu de res/animation/fragment_slide_right_enter.xmlfile.it contenait des balises d'animation d'ensemble et d'objet

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
   <objectAnimator
      android:interpolator="@android:interpolator/decelerate_quint"
      android:valueFrom="-100dp" android:valueTo="0dp"
      android:valueType="floatType"
      android:propertyName="translationX"
      android:duration="@android:integer/config_mediumAnimTime" />
   
   <objectAnimator
      android:interpolator="@android:interpolator/decelerate_quint"
      android:valueFrom="0.0" android:valueTo="1.0"
      android:valueType="floatType"
      android:propertyName="alpha"
      android:duration="@android:integer/config_mediumAnimTime" />
</set>

le code suivant sera le contenu de res/animation/fragment_slide_right_exit.xmlfichier, il contenait des balises d'animation d'ensemble et d'objet

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
   <objectAnimator
      android:interpolator="@android:interpolator/decelerate_quint"
      android:valueFrom="0dp" android:valueTo="100dp"
      android:valueType="floatType"
      android:propertyName="translationX"
      android:duration="@android:integer/config_mediumAnimTime" />
    
   <objectAnimator
      android:interpolator="@android:interpolator/decelerate_quint"
      android:valueFrom="1.0" android:valueTo="0.0"
      android:valueType="floatType"
      android:propertyName="alpha"
      android:duration="@android:integer/config_mediumAnimTime" />
</set>

le code suivant sera le contenu de src/main/java/MainActivity.javafichier. il contenait un écouteur de bouton, un fragment de pile et onCreateView

package com.example.fragmentcustomanimations;
 
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

import android.widget.Button;
import android.widget.TextView;
 
/**
 * Demonstrates the use of custom animations in a FragmentTransaction when
 * pushing and popping a stack.
 */
public class FragmentCustomAnimations extends Activity {
   int mStackLevel = 1;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.fragment_stack);
      
      // Watch for button clicks.
      Button button = (Button)findViewById(R.id.new_fragment);
      
      button.setOnClickListener(new OnClickListener() {
         public void onClick(View v) {
            addFragmentToStack();
         }
      });
      
      if (savedInstanceState == null) {
         // Do first time initialization -- add initial fragment.
         Fragment newFragment = CountingFragment.newInstance(mStackLevel);
         FragmentTransaction ft = getFragmentManager().beginTransaction();
         ft.add(R.id.simple_fragment, newFragment).commit();
      }
      else
      {
         mStackLevel = savedInstanceState.getInt("level");
      }
   }
   
   @Override
   public void onSaveInstanceState(Bundle outState) {
      super.onSaveInstanceState(outState);
      outState.putInt("level", mStackLevel);
   }
   
   void addFragmentToStack() {
      mStackLevel++;
   
      // Instantiate a new fragment.
      Fragment newFragment = CountingFragment.newInstance(mStackLevel);
   
      // Add the fragment to the activity, pushing this transaction
      // on to the back stack.
      FragmentTransaction ft = getFragmentManager().beginTransaction();
      ft.setCustomAnimations(R.animator.fragment_slide_left_enter,
      R.animator.fragment_slide_left_exit,
      R.animator.fragment_slide_right_enter,
      R.animator.fragment_slide_right_exit);
      ft.replace(R.id.simple_fragment, newFragment);
      ft.addToBackStack(null);
      ft.commit();
   }
   
   public static class CountingFragment extends Fragment {
      int mNum;
      /**
      * Create a new instance of CountingFragment, providing "num"
      * as an argument.
      */
      static CountingFragment newInstance(int num) {
         CountingFragment f = new CountingFragment();
          
         // Supply num input as an argument.
         Bundle args = new Bundle();
         args.putInt("num", num);
         f.setArguments(args);
         return f;
      }
      
      /**
      * When creating, retrieve this instance's number from its arguments.
      */
      
      @Override
      public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         mNum = getArguments() != null ? getArguments().getInt("num") : 1;
      }
      /**
      * The Fragment's UI is just a simple text view showing its
      * instance number.
      */
      
      @Override
      public View onCreateView(LayoutInflater inflater, 
         ViewGroup container,Bundle savedInstanceState) {
         View v = inflater.inflate(R.layout.hello_world, container, false);
         View tv = v.findViewById(R.id.text);
         ((TextView)tv).setText("Fragment #" + mNum);
         tv.setBackgroundDrawable(getResources().
            getDrawable(android.R.drawable.gallery_thumb));
         return v;
      }
   }
}

suivant sera le contenu de AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
   <manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.fragmentcustomanimations"
   android:versionCode="1"
   android:versionName="1.0" >
   
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
         
      <activity
         android:name="com.example.fragmentcustomanimations.MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
         
   </application>
</manifest>

Exécution de l'application

Essayons d'exécuter notre Fragment Transitionsapplication que nous venons de créer. Je suppose que vous avez créé votreAVDlors de la configuration de l'environnement. Pour exécuter l'application à partir d'Android Studio, ouvrez l'un des fichiers d'activité de votre projet et cliquez sur l' icône Exécuter dans la barre d'outils. Android installe l'application sur votre AVD et le démarre et si tout va bien avec votre configuration et votre application, il affichera la fenêtre Emulator suivante:

Si vous cliquez sur nouveau fragment, il va être changé le premier fragment en deuxième fragment comme indiqué ci-dessous