IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Android Discussion :

FragmentPagerAdapter instancie 3 fragments maximum


Sujet :

Android

  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Mai 2010
    Messages
    61
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Points : 42
    Points
    42
    Par défaut FragmentPagerAdapter instancie 3 fragments maximum
    Bonjour à tous,

    j'ai une application contenant 3 fragments.

    Lorsque je suis sur le fragment A, le B est instancié mais pas le C.
    Quand je suis sur le B, le A B et C sont instanciés.
    Quand je suis sur le C, le B et le C sont instanciés.

    Or j'aimerai avoir mes trois fragments instancié tout le temps! (pour pas mal de raisons, il y a une connexion à un serveur, ça améliorerait la vitesse, l'ergonomie etc...)

    Suite à quelque recherches j'ai compris que FragmentPagerAdapter instancie en effet que 3 fragments maximum (quand on est au "milieu"), mais j'aimerais qu'ils soient toujours instancié! Comment puis-je régler ce problème?


    Voici le code de mon activité principale:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
     
     
    package com.android.rss;
     
    import java.util.ArrayList;
    import java.util.List;
     
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentPagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.content.Context;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.MotionEvent;
    import android.view.View;
    import android.view.ViewGroup;
    import android.view.Window;
    import android.view.inputmethod.InputMethodManager;
    import android.widget.EditText;
     
     
    public class MainActivity extends FragmentActivity{
     
    	List<String> pages = new ArrayList<String>();
    	SectionsPagerAdapter mSectionsPagerAdapter;
     
    	private Fragment f;
    	/**
             * The {@link ViewPager} that will host the section contents.
             */
    	ViewPager mViewPager;
     
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
     
     
     
     
    		pages.add(MyFragmentA.class.getName());
    		pages.add(MyFragmentB.class.getName());
    		pages.add(MyFragmentC.class.getName());
     
    		mSectionsPagerAdapter = new SectionsPagerAdapter(super.getSupportFragmentManager(), this, pages);
     
     
    		// Set up the ViewPager with the sections adapter.
    		mViewPager = (ViewPager) findViewById(R.id.pager);
    		mViewPager.setAdapter(mSectionsPagerAdapter);
     
     
    	}
     
     
     	@Override
    	protected void onSaveInstanceState(Bundle outState) {
    	 	// TODO Auto-generated method stub
    	 	super.onSaveInstanceState(outState);
    		outState.putInt("SAVED_INDEX", getActionBar().getSelectedNavigationIndex());
    	}
     
     
     
     
     
     	@Override
     	public boolean onCreateOptionsMenu(Menu menu) {
     
     		return super.onCreateOptionsMenu(menu);
     	}
     
     
    	@Override
    	public boolean dispatchTouchEvent(MotionEvent event) {
     
    		//Lors d'un clic en dehors du clavier, il disparait
     
    		View view = getCurrentFocus();
    		boolean ret = super.dispatchTouchEvent(event);
     
    		if (view instanceof EditText) {
    		    View w = getCurrentFocus();
    		    int scrcoords[] = new int[2];
    		    w.getLocationOnScreen(scrcoords);
    		    float x = event.getRawX() + w.getLeft() - scrcoords[0];
    		    float y = event.getRawY() + w.getTop() - scrcoords[1];
     
    		    if (event.getAction() == MotionEvent.ACTION_UP 
    		    		&& (x < w.getLeft() || x >= w.getRight() 
    		    		|| y < w.getTop() || y > w.getBottom()) ) {
     
    		        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    		        imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
    		    }
    		}
    		return ret;
    	}
     
     
     
     	/** Rafraichi la page sur la quelle on est lors du click sur l'item "rafraichir"
             * @param Un MenuItem
             * @return true */
     	public boolean onOptionsItemSelected(MenuItem item){
     
     		return super.onOptionsItemSelected(item);
     	}
     
    	/**
             * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
             * one of the sections/tabs/pages.
             */
    	public class SectionsPagerAdapter extends FragmentPagerAdapter {
     
    		private Context mContext;
     
    	    private List<String> mClassNames;
     
    	    // On fournit à l'adapter la liste des fragments à afficher
    	    public SectionsPagerAdapter(FragmentManager fm, Context context, List<String> classNames) {
    	        super(fm);
    	        mContext=context;
    	        mClassNames = classNames;
     
    	        if(f == null)
    	        	f = Fragment.instantiate(mContext, mClassNames.get(0));
    	    }
     
     
     
    	    @Override
    	    public Fragment getItem(int position) {
     
    	        String className = mClassNames.get(position);
    	        if(position == 0)
    	        	return f;
    	        else
    	        	return Fragment.instantiate(mContext, className);
    	    }
     
    		@Override
    		public int getItemPosition(Object object) {
    		    return POSITION_NONE;
    		}
     
     
    		@Override
    		public int getCount() {
    			// Affiche 3 fragments
    			return 3;
    		}
     
    		@Override
    		public CharSequence getPageTitle(int position) {
     
    			//Retourne le nom du fragment
    			switch (position) {
    			case 0:
    				return getResources().getString(R.string.FragATxt);
    			case 1:
    				return getResources().getString(R.string.FragBTxt);
    			case 2:
    				return getResources().getString(R.string.FragCTxt);
    			}
     
    			return null;
    		}
     
     
    	}
     
    }


    Merci d'avance!

    Bien cordialement.

  2. #2
    Membre habitué
    Homme Profil pro
    Développeur Java
    Inscrit en
    Mai 2012
    Messages
    129
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 129
    Points : 144
    Points
    144
    Par défaut
    Pourquoi tu ne gère pas tes fragments de manières dynamique ?

    Exemple de mon FragmentPagerAdapter

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
     
    /**
         * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
         * one of the sections/tabs/pages.
         */
     
        // Ici tu peux très bien faire par exemple 
       FragmentA;
       FragmentB;
       FragmentC;
       .
       .
       .
       FragmentN;
        public class SectionsPagerAdapter extends FragmentPagerAdapter {
     
            public SectionsPagerAdapter(FragmentManager fm) {
                super(fm);
                FragmentA = FragmentA.newInstance();
                FragmentB = FragmentB.newInstance();
                FragmentC = FragmentC.newIntance();
                . 
                .
                FragmentN = FragmentN.newIntance();
            }
     
            @Override
            public Fragment getItem(int position) {
                // getItem is called to instantiate the fragment for the given page.
                // Return a PlaceholderFragment (defined as a static inner class below).
               switch(position) {
               case 1 : 
                   return FragmentA;
               case 2 : 
                   return FragmentB;
               case 3 :
                   return FragmentC;
               case 4 :
                   return FragmentN;
     
              }
            }
     
            @Override
            public int getCount() {
                // Show 3 total pages.
           // Ici tu modifie le nombre de Fragment que tu souhaite
                return 3;
            }
     
            @Override
            public CharSequence getPageTitle(int position) {
                Locale l = Locale.getDefault();
                switch (position) {
                    case 0:
                        return "Fragment A";
                    case 1:
                        return "Fragment B";
                    case 2:
                        return "Fragment C";
                    default:
                        return "Fragment N";
                }
                return null;
            }
        }
     
        public Fragment getFragmentA()
         {
              return FragmentA;
          }
        public Fragment getFragmentB()
         {
              return FragmentB;
          }
     
         public Fragment getFragmentC()
         {
              return FragmentC;
          }
     
        public Fragment getFragmentA()
        {
              return FragmentA;
        }

  3. #3
    Membre du Club
    Profil pro
    Inscrit en
    Mai 2010
    Messages
    61
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Points : 42
    Points
    42
    Par défaut
    J'avais déjà essayé, je viens de le refaire, mais j'ai le même résultat...

    Mon adapter:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    public class SectionsPagerAdapter extends FragmentPagerAdapter {
     
    		private Context mContext;
    	    private List<String> mClassNames;
     
     
     
    	    // On fournit à l'adapter la liste des fragments à afficher
    	    public SectionsPagerAdapter(FragmentManager fm, Context context, List<String> classNames) {
     
    	    	super(fm);
    	        mContext=context;
    	        mClassNames = classNames;
    	        fragmentA = Fragment.instantiate(mContext, mClassNames.get(0));
    	        fragmentB = Fragment.instantiate(mContext, mClassNames.get(1));
    	        fragmentC = Fragment.instantiate(mContext, mClassNames.get(2));
     
    	    }
     
     
     
    	    @Override
    	    public Fragment getItem(int position) {
     
    	    	switch(position) {
    	           case 0 : 
    	               return fragmentA;
    	           case 1 : 
    	               return fragmentB;
    	           case 2 :
    	               return fragmentC;
     
    	          }
     
    	    	return null;
    	    }
     
     
     
    		@Override
    		public int getItemPosition(Object object) {
    		    return POSITION_NONE;
    		}
     
     
     
     
    		@Override
    		public int getCount() {
    			// Affiche 3 fragments
    			return 3;
    		}
     
     
     
    		@Override
    		public CharSequence getPageTitle(int position) {
     
    			//Retourne le nom du fragment
    			switch (position) {
    			case 0:
    				return getResources().getString(R.string.FragATxt);
    			case 1:
    				return getResources().getString(R.string.FragBTxt);
    			case 2:
    				return getResources().getString(R.string.FragCTxt);
    			}
     
    			return null;
    		}
     
     
    	}

  4. #4
    Membre du Club
    Profil pro
    Inscrit en
    Mai 2010
    Messages
    61
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Points : 42
    Points
    42
    Par défaut
    J'ai trouvé ce site: http://alexfu.github.io/blog/2013/04...tpageradapter/

    Mais je ne comprend pas bien ce qu'il faut faire exactement...

  5. #5
    Membre habitué
    Homme Profil pro
    Développeur Java
    Inscrit en
    Mai 2012
    Messages
    129
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 129
    Points : 144
    Points
    144
    Par défaut
    Fait un getter dans le SectionPagerAdapter sur tes fragments et après tu récupères les instances ?

    un code du stye :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
     
    public Fragment getFragmentA()
    {
        return FragmentA;
    }
     
    public Fragment getFragmentB()
    {
        return FragmentB;
    }
     
    public Fragment getFragmentC()
    {
        return FragmentC;
    }

  6. #6
    Membre du Club
    Profil pro
    Inscrit en
    Mai 2010
    Messages
    61
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Points : 42
    Points
    42
    Par défaut
    Malheureusement, ça ne fonctionne pas Déjà est-ce possible ce que je demande avec un tel adapter?

  7. #7
    Membre habitué
    Homme Profil pro
    Développeur Java
    Inscrit en
    Mai 2012
    Messages
    129
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 129
    Points : 144
    Points
    144
    Par défaut
    Ça te retourne que tes fragments sont nuls ?

    Dans ton initiate tu fait bien un new FragmentA() ??

    Dans un projet récemment j'ai du le faire et ça fonctionner et dans un viewPager également...

  8. #8
    Membre du Club
    Profil pro
    Inscrit en
    Mai 2010
    Messages
    61
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Points : 42
    Points
    42
    Par défaut
    Non le fragment sur le quel je suis est instancié, celui à droite ou à gauche aussi mais pas les autres C'est un peu spécial comme problème à expliquer en fait... J'aimerais que tout mes fragments soient instanciés en même temps sinon quand je reviens sur un autre il doit recharger les donnée du serveur, ça prend une demi seconde car j'utilise le cache mais c'est un peu gênant quoi!

  9. #9
    Membre habitué
    Homme Profil pro
    Développeur Java
    Inscrit en
    Mai 2012
    Messages
    129
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 129
    Points : 144
    Points
    144
    Par défaut
    tu peux crée une instance de ce type

    public Fragment Instance

    if(Fragment == null)
    FragmentA = new FragmentA()

    return FragmentA;

  10. #10
    Membre du Club
    Profil pro
    Inscrit en
    Mai 2010
    Messages
    61
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Points : 42
    Points
    42
    Par défaut
    J'ai déjà essayé, mais je crois que l'adapter "retient" quels fragments il doit utiliser et les ré-instancie lui-même! Voilà pourquoi je pense qu'on ne peut pas faire ce que je veux faire
    Enfin après c'était pour un petit soucis d'ergonomie, ce n'est pas indispensable. En tout cas je te remercie de bien vouloir m'aider

  11. #11
    Membre habitué
    Homme Profil pro
    Développeur Java
    Inscrit en
    Mai 2012
    Messages
    129
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 129
    Points : 144
    Points
    144
    Par défaut
    Si tu n'as pas modifier ta partie du départ c'est normal...

    Sinon en aucun cas il doit réinstancier tes fragments temps que tu fait pas un new.

    A moins qu'il y est une subtilité avec ça.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    @Override
    	    public Fragment getItem(int position) {
     
    	        String className = mClassNames.get(position);
    	        if(position == 0)
    	        	return f;
    	        else
    	        	return Fragment.instantiate(mContext, className);
    	    }
    Quelqu'un pour confirmer ?

  12. #12
    Membre du Club
    Profil pro
    Inscrit en
    Mai 2010
    Messages
    61
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Points : 42
    Points
    42
    Par défaut
    Alors voilà j'ai tenté ça:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    	    @Override
    	    public Fragment getItem(int position) {
     
    	    	String name = makeFragmentName(R.id.pager, position);
    	        Fragment f = mFragmentManager.findFragmentByTag(name);
    	        if(f == null){
     
    	        	f = Fragment.instantiate(mContext, classNames.get(position));
    	        	return f;
     
    	        }
     
    	        else
    	        	return f;
     
     
    	    }
    Mais toujours pareil!

Discussions similaires

  1. Mettre à jour fragment FragmentPagerAdapter
    Par quichaci dans le forum Android
    Réponses: 2
    Dernier message: 09/12/2014, 07h00
  2. Réponses: 2
    Dernier message: 26/09/2014, 23h47
  3. Réponses: 0
    Dernier message: 04/09/2014, 22h46
  4. Réponses: 9
    Dernier message: 07/04/2014, 19h49
  5. Réponses: 1
    Dernier message: 15/10/2012, 16h07

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo