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

Composants graphiques Android Discussion :

Mettre une ListView dans un fragment ?


Sujet :

Composants graphiques Android

  1. #1
    Membre confirmé
    Inscrit en
    Avril 2002
    Messages
    86
    Détails du profil
    Informations personnelles :
    Âge : 46

    Informations forums :
    Inscription : Avril 2002
    Messages : 86
    Par défaut Mettre une ListView dans un fragment ?
    Bonjour,

    Je débute sous android.

    J'ai créer via eclipse un nouveau projet android. Lors de la création de celui-ci j'ai choisis comme type de navigation: "Swipe Views + Title Strip".

    Je lance l'appli et dans celle-ci je peux slider de droite a gauche entre mes 3 fragments. Dans ces derniers, il y a un textview indiquant le numéro du fragment.

    Par contre, coté développement, mon fichier activity_main.xml n'est plus éditable graphiquement.

    A priori, c'est du au fait que des fragments on été créés dans mon activité principale , mais comment faire pour associer des layouts a chaque fragment et comment mettre par exemple une listview dans un des fragment?

    Le code par defaut du mainactivity.java:
    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
    package com.example.test;
     
    import android.os.Bundle;
    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.app.NavUtils;
    import android.support.v4.view.ViewPager;
    import android.view.Gravity;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
     
    public class MainActivity extends FragmentActivity {
     
    	/**
             * The {@link android.support.v4.view.PagerAdapter} that will provide
             * fragments for each of the sections. We use a
             * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
             * will keep every loaded fragment in memory. If this becomes too memory
             * intensive, it may be best to switch to a
             * {@link android.support.v4.app.FragmentStatePagerAdapter}.
             */
    	SectionsPagerAdapter mSectionsPagerAdapter;
     
    	/**
             * The {@link ViewPager} that will host the section contents.
             */
    	ViewPager mViewPager;
     
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
     
    		// Create the adapter that will return a fragment for each of the three
    		// primary sections of the app.
    		mSectionsPagerAdapter = new SectionsPagerAdapter(
    				getSupportFragmentManager());
     
    		// Set up the ViewPager with the sections adapter.
    		mViewPager = (ViewPager) findViewById(R.id.pager);
    		mViewPager.setAdapter(mSectionsPagerAdapter);
     
    	}
     
    	@Override
    	public boolean onCreateOptionsMenu(Menu menu) {
    		// Inflate the menu; this adds items to the action bar if it is present.
    		getMenuInflater().inflate(R.menu.activity_main, menu);
    		return true;
    	}
     
    	/**
             * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
             * one of the sections/tabs/pages.
             */
    	public class SectionsPagerAdapter extends FragmentPagerAdapter {
     
    		public SectionsPagerAdapter(FragmentManager fm) {
    			super(fm);
    		}
     
    		@Override
    		public Fragment getItem(int position) {
    			// getItem is called to instantiate the fragment for the given page.
    			// Return a DummySectionFragment (defined as a static inner class
    			// below) with the page number as its lone argument.
    			Fragment fragment = new DummySectionFragment();
    			Bundle args = new Bundle();
    			args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
    			fragment.setArguments(args);
    			return fragment;
    		}
     
    		@Override
    		public int getCount() {
    			// Show 3 total pages.
    			return 3;
    		}
     
    		@Override
    		public CharSequence getPageTitle(int position) {
    			switch (position) {
    			case 0:
    				return getString(R.string.title_section1).toUpperCase();
    			case 1:
    				return getString(R.string.title_section2).toUpperCase();
    			case 2:
    				return getString(R.string.title_section3).toUpperCase();
    			}
    			return null;
    		}
    	}
     
    	/**
             * A dummy fragment representing a section of the app, but that simply
             * displays dummy text.
             */
    	public static class DummySectionFragment extends Fragment {
    		/**
                     * The fragment argument representing the section number for this
                     * fragment.
                     */
    		public static final String ARG_SECTION_NUMBER = "section_number";
     
    		public DummySectionFragment() {
    		}
     
    		@Override
    		public View onCreateView(LayoutInflater inflater, ViewGroup container,
    				Bundle savedInstanceState) {
    			// Create a new TextView and set its text to the fragment's section
    			// number argument value.
    			TextView textView = new TextView(getActivity());
    			textView.setGravity(Gravity.CENTER);
    			textView.setText(Integer.toString(getArguments().getInt(
    					ARG_SECTION_NUMBER)));
    			return textView;
    		}
    	}
     
    }
    Et le activity_main.xml
    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
    <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity" >
     
        <!--
        This title strip will display the currently visible page title, as well as the page
        titles for adjacent pages.
        -->
     
        <android.support.v4.view.PagerTitleStrip
            android:id="@+id/pager_title_strip"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="#33b5e5"
            android:paddingBottom="4dp"
            android:paddingTop="4dp"
            android:textColor="#fff" />
     
    </android.support.v4.view.ViewPager>
    Merci pour vos aides.

  2. #2
    Expert confirmé

    Avatar de Feanorin
    Profil pro
    Inscrit en
    Avril 2004
    Messages
    4 589
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 4 589
    Par défaut
    Bonjour,

    Tu peux charger des fichiers xml depuis tes fragments :

    exemple :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    public static class ExampleFragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.example_fragment, container, false);
        }
    }
    http://developer.android.com/guide/c...fragments.html

    Après tu peux toujours surcharger ta vue principale comme tu l'a fait dans ton code.

    Ici un exemple :
    http://sberfini.developpez.com/tutor...oid/fragments/

  3. #3
    Membre confirmé
    Inscrit en
    Avril 2002
    Messages
    86
    Détails du profil
    Informations personnelles :
    Âge : 46

    Informations forums :
    Inscription : Avril 2002
    Messages : 86
    Par défaut
    Bonjour,
    Merci pour ta réponse, je commencais à me sentir seul

    Depuis, j'ai fais pas mal de lecture car mes connaissances sont trop faibles....

    Bref, j'ai réussi, comme tu l'a indiqué à avoir un layout correspondant à chacun de mes fragments.

    Par contre maintenant je bloque sur un nouveau probleme......La Listview. Il y a des tonnes d'exemples sur le web pour mettre une listview dans un layout relié à une activité mais avec un fragment.....ce n'est pas tout à fait pareil car la méthode FindViewById n'existe pas....n'y l'arrayadapter.....

    Du coup, comment faire pour mettre une listeview dans ce layout (ca je le fais graphiquement), et surtout pour lui attribué du contenu?

    Merci,
    TouFou

  4. #4
    Expert confirmé

    Avatar de Feanorin
    Profil pro
    Inscrit en
    Avril 2004
    Messages
    4 589
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 4 589
    Par défaut
    Par contre maintenant je bloque sur un nouveau probleme......La Listview. Il y a des tonnes d'exemples sur le web pour mettre une listview dans un layout relié à une activité mais avec un fragment.....ce n'est pas tout à fait pareil car la méthode FindViewById n'existe pas....n'y l'arrayadapter.....


    Euh oui et non

    Tu n'as plus accès en direct puisque tu n'as plus le Context de ta vue principale (car elle se trouve maintenant dans le fragments), par contre tu peux le retrouver dans la view qui elle aura le bon contexte ^^ (la vue chargée ):

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
         View v = inflater.inflate(R.layout.frag_list_one, container, false);
         listView = (ListView) v.findViewById(R.id.frag_one_list);
         ladapter = new Adapter_CustomList(getActivity(), resultList);
         listView.setAdapter(adapter);
     }
    De même pour ton adapter tu peux faire un getActivity().

    Tu as tout dans l'exemple de la documentation officielle
    http://developer.android.com/referen.../Fragment.html

    Soit
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
      // Populate list with our static array of titles.
            setListAdapter(new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));

  5. #5
    Membre confirmé
    Inscrit en
    Avril 2002
    Messages
    86
    Détails du profil
    Informations personnelles :
    Âge : 46

    Informations forums :
    Inscription : Avril 2002
    Messages : 86
    Par défaut
    Merci beaucoup, cela marche du tonnerre!!

    Me reste plus qu'a afficher le contenu d'un fichier xml recuperer sur internet dans ma listeview et j'aurai ma première appli!



    TouFou

  6. #6
    Membre confirmé
    Inscrit en
    Avril 2002
    Messages
    86
    Détails du profil
    Informations personnelles :
    Âge : 46

    Informations forums :
    Inscription : Avril 2002
    Messages : 86
    Par défaut
    Je viens d'essayer de parser un fichier xml pour le mettre dans ma listview....


    Je me suis basé sur un tuto, j'ai récuperer ses classes, garder la meme url de fichier xml à recuperer, autoriser mon appli à aller sur le net.

    Et dans mon activité principale, j'ai mis le bout de code qui appelle le parser. et la à chaque fois mon appli plante avec le message d'erreur NetworkOnMainThreadException.

    De ce que j'ai compris, le probleme vient du fait d'appeler mon parser qui a un lien avec le net depuis mon activité principale.

    Du coup j'ai regarder pour faire un thread, mais là nouveau probleme, dans le thread avec les lignes:

    ListFeedAdapter lfa = new ListFeedAdapter(getActivity(), feeds);
    ((ListView) rootView.findViewById(R.id.lvListe)).setAdapter(lfa);
    rootView.findViewById n'est pas trouvé car je ne suis plus dans le onCreateView de ma classe DummySectionFragment....


    Comment faire pour faire le lien?

  7. #7
    Expert confirmé

    Avatar de Feanorin
    Profil pro
    Inscrit en
    Avril 2004
    Messages
    4 589
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 4 589
    Par défaut
    Bonjour,

    Il faut que tu sauvegarde ta liste dans une variable, après si ton Thread n'est pas une classe anonyme alors il te faudra passer par un Handler pour prévenir ton fragment de mettre sa liste à jour.

  8. #8
    Membre confirmé
    Inscrit en
    Avril 2002
    Messages
    86
    Détails du profil
    Informations personnelles :
    Âge : 46

    Informations forums :
    Inscription : Avril 2002
    Messages : 86
    Par défaut
    Bonsoir Feanorin,

    J'ai passé ma soirée à essayer de comprendre et appliquer ta réponse......

    J'ai mis un thread pour récupérer mes données et faire l'affichage dans la listview. Au final je me retrouve avec une nouvelle erreur:
    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
    01-23 23:35:15.020: D/dalvikvm(19797): GC_CONCURRENT freed 235K, 11% free 3928K/4392K, paused 3ms+3ms, total 22ms
    01-23 23:35:15.030: W/dalvikvm(19797): threadid=11: thread exiting with uncaught exception (group=0x41feb930)
    01-23 23:35:15.035: E/AndroidRuntime(19797): FATAL EXCEPTION: Thread-6357
    01-23 23:35:15.035: E/AndroidRuntime(19797): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
    01-23 23:35:15.035: E/AndroidRuntime(19797): 	at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4746)
    01-23 23:35:15.035: E/AndroidRuntime(19797): 	at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:854)
    01-23 23:35:15.035: E/AndroidRuntime(19797): 	at android.view.ViewGroup.invalidateChild(ViewGroup.java:4077)
    01-23 23:35:15.035: E/AndroidRuntime(19797): 	at android.view.View.invalidate(View.java:10379)
    01-23 23:35:15.035: E/AndroidRuntime(19797): 	at android.view.View.invalidate(View.java:10334)
    01-23 23:35:15.035: E/AndroidRuntime(19797): 	at android.widget.AbsListView.resetList(AbsListView.java:1840)
    01-23 23:35:15.035: E/AndroidRuntime(19797): 	at android.widget.ListView.resetList(ListView.java:504)
    01-23 23:35:15.035: E/AndroidRuntime(19797): 	at android.widget.ListView.setAdapter(ListView.java:444)
    01-23 23:35:15.035: E/AndroidRuntime(19797): 	at fr.fccoop13.MainActivity$DummySectionFragment$1.run(MainActivity.java:220)
    01-23 23:35:15.035: E/AndroidRuntime(19797): 	at java.lang.Thread.run(Thread.java:856)
    01-23 23:35:15.995: D/AndroidRuntime(19797): Shutting down VM
    01-23 23:35:15.995: W/dalvikvm(19797): threadid=1: thread exiting with uncaught exception (group=0x41feb930)
    01-23 23:35:15.995: I/Process(19797): Sending signal. PID: 19797 SIG: 9

    Je crois que je suis paumé entre les endroits ou l'on doit créer ses variables, les utiliser et autres.....

    Ci dessous mon code.
    Dans la méthode onCreateView de la classe DummySectionFragment , pour le case 1, correspondant à mon premier fragment, j'appelle la fonction traitementDesDonnees qui me donne l'erreur ci-dessus.

    Je tourne en rond et suis un peu paumé....
    Si tu arrives à comprendre mon problème et à m'aider, tant mieux

    Mon code:
    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
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    package fr.fccoop13;
     
    import java.util.ArrayList;
    import android.os.Bundle;
    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.view.LayoutInflater;
    import android.view.Menu;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import fr.fccoop13.R;
    import fr.fccoop13.ContainerData;
    import fr.fccoop13.Feed;
    import fr.fccoop13.ListFeedAdapter;
     
     
     
     
    public class MainActivity extends FragmentActivity {
     
     
    	static ArrayList<Feed> feeds_actu;
     
     
    	/**
             * The {@link android.support.v4.view.PagerAdapter} that will provide
             * fragments for each of the sections. We use a
             * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
             * will keep every loaded fragment in memory. If this becomes too memory
             * intensive, it may be best to switch to a
             * {@link android.support.v4.app.FragmentStatePagerAdapter}.
             */
    	SectionsPagerAdapter mSectionsPagerAdapter;
     
    	/**
             * The {@link ViewPager} that will host the section contents.
             */
    	ViewPager mViewPager;
     
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
     
     
     
    		// Create the adapter that will return a fragment for each of the three
    		// primary sections of the app.
    		mSectionsPagerAdapter = new SectionsPagerAdapter(
    				getSupportFragmentManager());
     
    		// Set up the ViewPager with the sections adapter.
    		mViewPager = (ViewPager) findViewById(R.id.pager);
    		mViewPager.setAdapter(mSectionsPagerAdapter);
     
     
     
    	}
     
    	@Override
    	public boolean onCreateOptionsMenu(Menu menu) {
    		// Inflate the menu; this adds items to the action bar if it is present.
    		getMenuInflater().inflate(R.menu.activity_main, menu);
    		return true;
    	}
     
    	/**
             * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
             * one of the sections/tabs/pages.
             */
     
    	public class SectionsPagerAdapter extends FragmentPagerAdapter {
     
    		public SectionsPagerAdapter(FragmentManager fm) {
    			super(fm);
    		}
     
    		@Override
    		public Fragment getItem(int position) {
    			// getItem is called to instantiate the fragment for the given page.
    			// Return a DummySectionFragment (defined as a static inner class
    			// below) with the page number as its lone argument.
    			Fragment fragment = new DummySectionFragment();
    			Bundle args = new Bundle();
    			args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
    			fragment.setArguments(args);
    			return fragment;
    		}
     
    		@Override
    		public int getCount() {
    			// Show 5 total pages.
    			return 5;
    		}
     
     
    		@Override
    		public CharSequence getPageTitle(int position) {
    			switch (position) {
    			case 0:  
    				return getString(R.string.title_section1).toUpperCase();
    			case 1:
    				return getString(R.string.title_section2).toUpperCase();
    			case 2:
    				return getString(R.string.title_section3).toUpperCase();
    			case 3:
    				return getString(R.string.title_section4).toUpperCase();
    			case 4:
    				return getString(R.string.title_section5).toUpperCase();
    			}
    			return null;
    		}
    	}
    	/**
             * A dummy fragment representing a section of the app, but that simply
             * displays dummy text.
             */
    	public static class DummySectionFragment extends Fragment {
    		/**
                     * The fragment argument representing the section number for this
                     * fragment.
                     */
     
    		ListView lvListe;
     
    		public static final String ARG_SECTION_NUMBER = "section_number";
     
     
    		public DummySectionFragment() {
     
     
    		}
     
    		@Override
    		public View onCreateView(LayoutInflater inflater, ViewGroup container,
    				Bundle savedInstanceState) {
     
     
     
    			switch (Integer.parseInt(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)))) {
    			case 1:  
    				ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment1, container, false);
     
    			    lvListe = (ListView) rootView.findViewById(R.id.lvListe);
    		         //   String[] listeStrings = {"France1","Allemagne1","Russie1","France1","Allemagne1","Russie1","France1","Allemagne1","Russie1","France1","Allemagne1","Russie1","France1","Allemagne1","Russie1",};
    		        //   lvListe.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,listeStrings));
     
    		           traitementDesDonnees();
     
    		           return rootView;
    			case 2:
    				ViewGroup rootView2 = (ViewGroup) inflater.inflate(
    					       R.layout.fragment2, container, false);
    			     lvListe = (ListView) rootView2.findViewById(R.id.lvListe);
    		            String[] listeStrings2 = {"FC Coop 13","FC Coop 13","Coupe de France"};
    		           lvListe.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,listeStrings2));
    					        return rootView2;
    			case 3:
    				ViewGroup rootView3 = (ViewGroup) inflater.inflate(
    					       R.layout.fragment3, container, false);
    					        lvListe = (ListView) rootView3.findViewById(R.id.lvListe);
    				            String[] listeStrings3 = {"FC Coop 13","Equipe 2","Equipe 1"};
    				           lvListe.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,listeStrings3));
    					        return rootView3;
    			case 4:
    				ViewGroup rootView4 = (ViewGroup) inflater.inflate(
    					       R.layout.fragment4, container, false);
    		        lvListe = (ListView) rootView4.findViewById(R.id.lvListe);
    	            String[] listeStrings4 = {"France4","Allemagne4","Russie4"};
    	           lvListe.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,listeStrings4));
     
    					        return rootView4;
    			case 5:
    				ViewGroup rootView5 = (ViewGroup) inflater.inflate(
    					       R.layout.fragment5, container, false);
    		        lvListe = (ListView) rootView5.findViewById(R.id.lvListe);
    	            String[] listeStrings5 = {"France5","Allemagne5","Russie5"};
    	           lvListe.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,listeStrings5));
     
    					        return rootView5;
    			}
    			return null;
     
     
    		}
     
    		private void traitementDesDonnees() {
     
    			new Thread(new Runnable() {
     
    			@Override
     
    			public void run() {
    				feeds_actu= ContainerData.getFeeds();
    			    ListFeedAdapter lfa = new ListFeedAdapter(getActivity(), feeds_actu);
    			    lvListe.setAdapter(lfa);
    			}
     
    			}).start();
     
    			}
     
     
     
    	}
     
    }
    Suis-je loin du compte?

    Bonne soirée,
    TouFou

  9. #9
    Expert confirmé

    Avatar de Feanorin
    Profil pro
    Inscrit en
    Avril 2004
    Messages
    4 589
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 4 589
    Par défaut
    .

    Ici

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    new Thread(new Runnable() {
     
    			@Override
     
    			public void run() {
    				feeds_actu= ContainerData.getFeeds();
    			    ListFeedAdapter lfa = new ListFeedAdapter(getActivity(), feeds_actu);
    			    lvListe.setAdapter(lfa);
    			}
     
    			}).start();
     
    			}
    Ta liste ne doit pas être traiter dans un Thread différent de l'UIThread.

    Après il me semble que ce que je voulais dire et que le traitement du fichier xml doit être fait dans un Thread séparé qui lui enverra un message lorsque ce traitement sera fini à l'UIThread. Après si ton thread est une classe anonyme de ton activity tu peux le jouer comme cela (runOnUIThread):

    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
    new Thread(new Runnable() {
     
    			@Override
     
    			public void run() {
    				feeds_actu= ContainerData.getFeeds();
                                    UpdateList(feeds_actu);
     
    			}
     
    			}).start();
     
     public void UpdateList(String resultat)
        {
        	//Déposer le Runnable dans la file d'attente de l'UI thread
        	runOnUiThread(new Runnable() {
               @Override
               public void run() {
               		//code exécuté par l'UI thread
                	   ListFeedAdapter lfa = new ListFeedAdapter(getActivity(), feeds_actu);
    			    lvListe.setAdapter(lfa);
                }
            });
        }
    Mais bon là on est pas optimisé :/

    Tu peux passer par un AsyncTask au final, je pense que cela pourrait correspondre à tes besoins.

    Après pour expliquer mon message

    Il faut que tu sauvegarde ta liste dans une variable,
    Je pensais que tu utiliser le même adapter, du coup se passage est foireux . SI c'était le cas il te suffisait de mettre à jour les données de la liste puis de notifier à la liste de se mettre à jour.

    Edit:

    Regarde ce tutoriel :
    http://davy-leggieri.developpez.com/...oid/ui-thread/

  10. #10
    Membre confirmé
    Inscrit en
    Avril 2002
    Messages
    86
    Détails du profil
    Informations personnelles :
    Âge : 46

    Informations forums :
    Inscription : Avril 2002
    Messages : 86
    Par défaut
    Bonsoir Feanorin,

    J'ai commencé ma soirée par faire un copier coller de ton code
    J'ai une une erreur au niveau du runOnUIThread......
    Du coup, j'ai lu le tutorial que tu as indiqué. Vraiment très bien fais pour un débutant comme moi!! Du coup, thread, thead UI et runOnUIThread ne me font plus peur
    Et je comprend mieux pourquoi devoir faire les traitements "lourd" dans un thread.
    Du coup, j'ai essayer de faire moi meme le thread depuis le tuto. Au final, je me retrouve avec le meme code que toi au nom de la fonction près.....
    Et je me retrouve quand meme avec la même erreur...suspens....

    runOnUIThread est souligné en rouge et quand je passe la souris dessus il est indiqué:
    Cannot make a static reference to the non-static method runOnUiThread(Runnable) from the type Activity

    J'avoue ne rien comprendre....
    Peux-tu m'expliquer?
    Je sens que j'y suis presque

  11. #11
    Expert confirmé

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Billets dans le blog
    3
    Par défaut
    Si tu laisses le pointeur sur la fonction tu verras aussi du javadoc... (ou sinon developper.android.com recherche 'runOnUIThread').
    Il est indiqué que c'est une fonction (non statique) de la classe "Activity"

    Pour pouvoir l'appeler il te faut donc un objet de type "Activity"

  12. #12
    Membre confirmé
    Inscrit en
    Avril 2002
    Messages
    86
    Détails du profil
    Informations personnelles :
    Âge : 46

    Informations forums :
    Inscription : Avril 2002
    Messages : 86
    Par défaut
    Ok, merci pour l'explication.

    Mais du coup dans mon cas, comment faire vu que je suis dans un fragment ? Il existe un équivalent à runOnUIThread pour le fragment ?

    TouFou

  13. #13
    Expert confirmé

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Billets dans le blog
    3
    Par défaut
    Citation Envoyé par feanorin
    De même pour ton adapter tu peux faire un getActivity().

    Tu as tout dans l'exemple de la documentation officielle
    http://developer.android.com/referen.../Fragment.html
    Bien lire les réponses peut aider.... Le fragment appartien à une Activity, et on peut récupérer l'Activity à tout moment.

  14. #14
    Membre confirmé
    Inscrit en
    Avril 2002
    Messages
    86
    Détails du profil
    Informations personnelles :
    Âge : 46

    Informations forums :
    Inscription : Avril 2002
    Messages : 86
    Par défaut
    Merci Nicroman, cela fonctionne!


    Comme je l'ai dis au début, je suis débutant est un peu perdu!! Du coup, ce n’était pas évident pour moi de voir la soluce même écrite plus haut.....

    TouFou

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

Discussions similaires

  1. [Débutant] Mettre une listBox dans une colonne d'une listView
    Par Tom57300 dans le forum VB.NET
    Réponses: 1
    Dernier message: 23/04/2014, 15h40
  2. Réponses: 0
    Dernier message: 07/09/2013, 00h12
  3. Mettre une image dans un SubItem (listview)
    Par Hellgast dans le forum C++Builder
    Réponses: 6
    Dernier message: 22/05/2012, 23h18
  4. [Drag & Drop] Mettre une fiche dans un panel
    Par corwin_d_ambre dans le forum Composants VCL
    Réponses: 5
    Dernier message: 12/01/2004, 10h46
  5. Peut on mettre une image dans une BD MySQL ?
    Par maddog2032 dans le forum SQL Procédural
    Réponses: 3
    Dernier message: 25/07/2003, 16h18

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