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 :

Modifier texte tab host (fragment)


Sujet :

Android

  1. #1
    Membre éclairé
    Inscrit en
    Décembre 2008
    Messages
    483
    Détails du profil
    Informations forums :
    Inscription : Décembre 2008
    Messages : 483
    Par défaut Modifier texte tab host (fragment)
    Bonjour,

    J'aimerais changer le texte de l'un de mes onglets (d'un tabhost) lors d'un évènement (clik button).

    Je m'explique :

    1ère étape : Tab1 | Tab2
    2ème étape : : je clique sur un bouton situé sur le fragment1 (Tab1)
    3ème étape : au clique du bouton, le texte Tab2 doit être changé en TabChanged
    étape 4 : mon tabhost ressemble à ceci : Tab1| TabChanged

    Sauf que l'étape 3 coince... puisque je n'arrive pas à accéder à mon tabHost depuis le fragment 1.

    Voici le code du fragment principal (qui contient 2 fragment), TabFragmentActivity :
    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
     
    public class TabsFragmentActivity extends FragmentActivity implements TabHost.OnTabChangeListener {
     
        private TabHost mTabHost;
        private HashMap mapTabInfo = new HashMap();
        private TabInfo mLastTab = null;
     
        private class TabInfo {
             private String tag;
             private Class clss;
             private Bundle args;
             private Fragment fragment;
             TabInfo(String tag, Class clazz, Bundle args) {
                 this.tag = tag;
                 this.clss = clazz;
                 this.args = args;
             }
     
        }
     
        class TabFactory implements TabContentFactory {
     
            private final Context mContext;
     
            /**
             * @param context
             */
            public TabFactory(Context context) {
                mContext = context;
            }
     
            /** (non-Javadoc)
             * @see android.widget.TabHost.TabContentFactory#createTabContent(java.lang.String)
             */
            public View createTabContent(String tag) {
                View v = new View(mContext);
                v.setMinimumWidth(0);
                v.setMinimumHeight(0);
                return v;
            }
     
        }
        /** (non-Javadoc)
         * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
         */
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Step 1: Inflate layout
            setContentView(R.layout.tabs_layout);
            // Step 2: Setup TabHost
            initialiseTabHost(savedInstanceState);
            if (savedInstanceState != null) {
                mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab")); //set the tab as per the saved state
            }
        }
     
        /** (non-Javadoc)
         * @see android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os.Bundle)
         */
        protected void onSaveInstanceState(Bundle outState) {
            outState.putString("tab", mTabHost.getCurrentTabTag()); //save the tab selected
            super.onSaveInstanceState(outState);
        }
     
        /**
         * Step 2: Setup TabHost
         */
        private void initialiseTabHost(Bundle args) {
            mTabHost = (TabHost)findViewById(android.R.id.tabhost);       
            mTabHost.setup();
            TabInfo tabInfo = null;
            TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab1").setIndicator("Tab 1"), ( tabInfo = new TabInfo("Tab1", TabFragment1.class, args)));
            this.mapTabInfo.put(tabInfo.tag, tabInfo);
            TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator("Tab 2"), ( tabInfo = new TabInfo("Tab2", TabFragment2.class, args)));
            this.mapTabInfo.put(tabInfo.tag, tabInfo);
            TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab 3"), ( tabInfo = new TabInfo("Tab3", TabFragment3.class, args)));
            this.mapTabInfo.put(tabInfo.tag, tabInfo);
            // Default to first tab
            this.onTabChanged("Tab1");
            //
            mTabHost.setOnTabChangedListener(this);
        }
     
        /**
         * @param activity
         * @param tabHost
         * @param tabSpec
         * @param clss
         * @param args
         */
        private static void addTab(TabsFragmentActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) {
            // Attach a Tab view factory to the spec
            tabSpec.setContent(activity.new TabFactory(activity));
            String tag = tabSpec.getTag();
     
            // Check to see if we already have a fragment for this tab, probably
            // from a previously saved state.  If so, deactivate it, because our
            // initial state is that a tab isn't shown.
            tabInfo.fragment = activity.getSupportFragmentManager().findFragmentByTag(tag);
            if (tabInfo.fragment != null && !tabInfo.fragment.isDetached()) {
                FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
                ft.detach(tabInfo.fragment);
                ft.commit();
                activity.getSupportFragmentManager().executePendingTransactions();
            }
     
            tabHost.addTab(tabSpec);
        }
     
        /** (non-Javadoc)
         * @see android.widget.TabHost.OnTabChangeListener#onTabChanged(java.lang.String)
         */
        public void onTabChanged(String tag) {
            TabInfo newTab = (TabInfo) this.mapTabInfo.get(tag);
            if (mLastTab != newTab) {
                FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
                if (mLastTab != null) {
                    if (mLastTab.fragment != null) {
                        ft.detach(mLastTab.fragment);
                    }
                }
                if (newTab != null) {
                    if (newTab.fragment == null) {
                        newTab.fragment = Fragment.instantiate(this,
                                newTab.clss.getName(), newTab.args);
                        ft.add(R.id.realtabcontent, newTab.fragment, newTab.tag);
                    } else {
                        ft.attach(newTab.fragment);
                    }
                }
     
                mLastTab = newTab;
                ft.commit();
                this.getSupportFragmentManager().executePendingTransactions();
            }
        }
     
    }
    Et le TabFragment1 correspondant à l'onget Tab1 :

    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
    public class TabFragment1 extends Fragment {
        /** (non-Javadoc)
         * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
         */
     
        private Button button1;
     
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            if (container == null) {
                // We have different layouts, and in one of them this
                // fragment's containing frame doesn't exist.  The fragment
                // may still be created from its saved state, but there is
                // no reason to try to create its view hierarchy because it
                // won't be displayed.  Note this is not needed -- we could
                // just run the code below, where we would create and return
                // the view hierarchy; it would just never be used.
                return null;
            }
     
            LinearLayout mLinearLayout = (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout, container, false);
     
            button1 = (Button) mLinearLayout.findViewById(R.id.button1);
            button1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Log.d("aaa", "button_content_new");
     
    //CELA DOIT SE FAIRE ICI 
                 }
            });
     
            return mLinearLayout;
        }
    }
    C'est dans ce dernier code que je dois changer l'intitulé de mon onglet, mais impossible d'accéder au tabhost...

    Merci d'avance.

  2. #2
    Membre averti
    Inscrit en
    Janvier 2011
    Messages
    19
    Détails du profil
    Informations forums :
    Inscription : Janvier 2011
    Messages : 19
    Par défaut
    Tu as essayé de le récupérer via l'activité?

  3. #3
    Membre éclairé
    Inscrit en
    Décembre 2008
    Messages
    483
    Détails du profil
    Informations forums :
    Inscription : Décembre 2008
    Messages : 483
    Par défaut
    Et bien j'ai essayé ça dans mon Fragment1:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    private TabHost mTabHost;
    mTabHost = (TabHost)mLinearLayout.findViewById(android.R.id.tabhost);
    Mais comment modifier le texte d'un item... (surtout que je ne suis pas spur de bien récupérer le tabHost avec cette méthode)

  4. #4
    Membre averti
    Inscrit en
    Janvier 2011
    Messages
    19
    Détails du profil
    Informations forums :
    Inscription : Janvier 2011
    Messages : 19
    Par défaut
    Pour renommer tu peux essayer ça

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    LinearLayout layout = (LinearLayout) tabHost.getTabWidget().getChildAt(tabindex);
    ((TextView) layout.getChildAt(1)).setText("Tab indicator text");

  5. #5
    Membre éclairé
    Inscrit en
    Décembre 2008
    Messages
    483
    Détails du profil
    Informations forums :
    Inscription : Décembre 2008
    Messages : 483
    Par défaut
    Cela ne fonctionne pas. J'ai un Java nul pointer exception sur la première ligne.

  6. #6
    Membre averti
    Inscrit en
    Janvier 2011
    Messages
    19
    Détails du profil
    Informations forums :
    Inscription : Janvier 2011
    Messages : 19
    Par défaut
    C'est le tabhost qui est null?
    Si oui c'est qu'il faut le récupérer autrement.
    Tu peu accèder à ton activité avec la méthode getActivity() depuis ton fragment. Tu devrais pouvoir récupérer avec l'activité.

  7. #7
    Membre éclairé
    Inscrit en
    Décembre 2008
    Messages
    483
    Détails du profil
    Informations forums :
    Inscription : Décembre 2008
    Messages : 483
    Par défaut
    Oui il y a une erreur lors de la récupération du tabHost.

    Comment utiliser le getActivity()?

    Comme ceci ?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    this.getActivity().findViewById(id)

  8. #8
    Membre averti
    Inscrit en
    Janvier 2011
    Messages
    19
    Détails du profil
    Informations forums :
    Inscription : Janvier 2011
    Messages : 19
    Par défaut
    Oui ca devrais le faire.
    Sinon comme tu as le tabhost en attribut dans ton activité, tu peux créer une méthode dans ton activité pour le récupérer genre :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    public TabHost getTabhost() {
    return mTabHost;
    }
    Après je sais pas si c'est le moyen le plus élégant de faire ça mais ça devrait marcher.

  9. #9
    Membre éclairé
    Inscrit en
    Décembre 2008
    Messages
    483
    Détails du profil
    Informations forums :
    Inscription : Décembre 2008
    Messages : 483
    Par défaut
    tu as le tabhost en attribut dans ton activité
    Euh ? Je ne suis pas sûr de te suivre...

    Puis, pour le getActivity(), je me demande comment je peux l'utiliser dans mon cas

  10. #10
    Membre averti
    Inscrit en
    Janvier 2011
    Messages
    19
    Détails du profil
    Informations forums :
    Inscription : Janvier 2011
    Messages : 19
    Par défaut
    Désolé si c'est pas clair

    Normalement depuis un fragment (TabFragment1 dans ton cas) tu peux appeler la méthode getActivity() qui te retourne l'activité dans lequel ton fragment est situé.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    public void onClick(View v) {
                    Log.d("aaa", "button_content_new");
                   //CELA DOIT SE FAIRE ICI 
                   TabsFragmentActivity activity = TabFragment1.this.getActivity(); //Ca doit te retourner l'activité
                   activity.findViewById(id); //C'est la que tu récupère le tabhost
    }

  11. #11
    Membre éclairé
    Inscrit en
    Décembre 2008
    Messages
    483
    Détails du profil
    Informations forums :
    Inscription : Décembre 2008
    Messages : 483
    Par défaut
    Sur le principe, je suis d'accord. Mais sur la mise en place, ça coince vraiment.

    Déjà pour la première ligne il m'indique

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    cannot convert from FragmentActivity to TabsFragmentActivity
    (la classe qui gère les différents fragments est de type FragmentActivity)

    Ensuite, la deuxième est à compléter non?

    Genre comme ceci?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    mTabHost = (TabHost)activity.findViewById(R.id.tabHost);

  12. #12
    Membre averti
    Inscrit en
    Janvier 2011
    Messages
    19
    Détails du profil
    Informations forums :
    Inscription : Janvier 2011
    Messages : 19
    Par défaut
    Citation Envoyé par piero53 Voir le message
    Déjà pour la première ligne il m'indique

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    cannot convert from FragmentActivity to TabsFragmentActivity
    (la classe qui gère les différents fragments est de type FragmentActivity)
    Il faut que tu caste l'activité que tu récupères.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    TabsFragmentActivity activity = (TabsFragmentActivity)TabFragment1.this.getActivity();
    Citation Envoyé par piero53 Voir le message
    Ensuite, la deuxième est à compléter non?

    Genre comme ceci?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    mTabHost = (TabHost)activity.findViewById(R.id.tabHost);
    Oui, c'est ça

  13. #13
    Membre éclairé
    Inscrit en
    Décembre 2008
    Messages
    483
    Détails du profil
    Informations forums :
    Inscription : Décembre 2008
    Messages : 483
    Par défaut
    Ok, cela donnerais donc ça au final :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    TabsFragmentActivity activity = (TabsFragmentActivity) TabFragment1.this.getActivity();
    mTabHost = (TabHost)activity.findViewById(R.id.realtabcontent);
    LinearLayout layout = (LinearLayout) mTabHost.getTabWidget().getChildAt(0);
    ((TextView) layout.getChildAt(1)).setText("AA");

    Mais cela ne marche pas, j'ai une erreur sur la 2ème ligne :

    android.widget.FrameLayout cannot be cast to android.widget.TabHost

  14. #14
    Membre averti
    Inscrit en
    Janvier 2011
    Messages
    19
    Détails du profil
    Informations forums :
    Inscription : Janvier 2011
    Messages : 19
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    mTabHost = (TabHost)activity.findViewById(R.id.realtabcontent);
    Dans ton activité tu récupérais ton tabhost avec une autre ID, tu l'as changé en cours de route? Parce que la apparement tu récupère plutot le layout contenant ton fragment.

    Dans ton activité tu le récupèrai comme ça
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    private void initialiseTabHost(Bundle args) {
            mTabHost = (TabHost)findViewById(android.R.id.tabhost); 
           ....
    }

  15. #15
    Membre éclairé
    Inscrit en
    Décembre 2008
    Messages
    483
    Détails du profil
    Informations forums :
    Inscription : Décembre 2008
    Messages : 483
    Par défaut
    Pour que cela soit plus clair, coivi le code xml du fichier tabs_layout qui contient le tabHost:

    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
    <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
        <TabHost
            android:id="@android:id/tabhost"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            >
            <LinearLayout
                android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                >
     
                <TabWidget
                    android:id="@android:id/tabs"
                    android:orientation="horizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="0"
                    />
     
                <FrameLayout
                    android:id="@android:id/tabcontent"
                    android:layout_width="0dp"
                    android:layout_height="0dp"
                    android:layout_weight="0"/>
     
                <FrameLayout
                    android:id="@+android:id/realtabcontent"
                    android:layout_width="fill_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1"/>
            </LinearLayout>
        </TabHost>
    </LinearLayout>
    Pour changer le texte du tabHost il faut donc que je récupère "tabhost" ?

    Ce qui donnera donc : (seulement la 2ème ligne a changé)

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    TabsFragmentActivity activity = (TabsFragmentActivity) TabFragment1.this.getActivity();
    mTabHost = (TabHost)activity.findViewById(R.layout.tabs_layout);
    LinearLayout layout = (LinearLayout) mTabHost.getTabWidget().getChildAt(0);
    ((TextView) layout.getChildAt(1)).setText("AA");
    Mais j'ai maintenant un nul pointer exception sur la 3ème ligne. Normal?

  16. #16
    Membre averti
    Inscrit en
    Janvier 2011
    Messages
    19
    Détails du profil
    Informations forums :
    Inscription : Janvier 2011
    Messages : 19
    Par défaut
    Non, tu dois récupérer ton tabhost. Je me suis mal exprimé dans le com précédent. Tu essayai de récupérer ton tabhost mais tu récupérait le layout contenant ton fragment (pour ça qu'il te disait qu'il ne pouvais pas convertir le frameLayout en tabhost).
    Donc il faut bien que tu récupère le tabhost.

    Dans ton xml tu lui a donné "tabhost" comme id.
    Et d'ailleurs dans ton activité tu le récupère avec
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    mTabHost = (TabHost)findViewById(android.R.id.tabhost);
    Donc là c'est pareil tu le récupère avec le même id.

    Au final ca devrait donner
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    TabsFragmentActivity activity = (TabsFragmentActivity) TabFragment1.this.getActivity();
    mTabHost = (TabHost)activity.findViewById(android.R.id.tabhost);
    LinearLayout layout = (LinearLayout) mTabHost.getTabWidget().getChildAt(0);
    ((TextView) layout.getChildAt(1)).setText("AA");

  17. #17
    Membre éclairé
    Inscrit en
    Décembre 2008
    Messages
    483
    Détails du profil
    Informations forums :
    Inscription : Décembre 2008
    Messages : 483
    Par défaut
    Ok, cela fonctionne.

    Merci beaucoup pour ton aide, vraiment.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. liste modifiable texte trop long
    Par samtheh dans le forum VBA Access
    Réponses: 3
    Dernier message: 27/06/2007, 21h18
  2. modifier texte de la barre des titres
    Par snakemetalgear dans le forum C
    Réponses: 4
    Dernier message: 12/06/2007, 17h22
  3. [Dreamweaver] Modifier texte dans une image
    Par Aspic dans le forum Dreamweaver
    Réponses: 4
    Dernier message: 13/04/2007, 18h17
  4. [JDOM] Modifier texte avec jdom
    Par thanatos67 dans le forum Format d'échange (XML, JSON...)
    Réponses: 2
    Dernier message: 07/03/2007, 15h21
  5. comment modifier texte paragraphe
    Par calitom dans le forum Général JavaScript
    Réponses: 1
    Dernier message: 24/11/2006, 18h36

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