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 :

Faire tourner un menuItem (une flèche)


Sujet :

Android

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

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Par défaut Faire tourner un menuItem (une flèche)
    Bonjour à tous,

    J'ai réalisé une application de flux RSS, pour rafraichir ma liste d'actualité, j'ai mis un menuItem qui est une flèche en "rond". Lors du click sur cette flèche, la liste est bien rafraichi.

    J'aimerais la faire tourner lors du chargement. Il y a assez peu de tuto sur ce cas précis. Comment faire tourner un MenuItem?



    Merci d'avance

  2. #2
    Rédacteur
    Avatar de David55
    Homme Profil pro
    Ingénieur informatique
    Inscrit en
    Août 2010
    Messages
    1 542
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2010
    Messages : 1 542
    Par défaut Ca tourne...
    Voici le code qui permet de faire tourner une ImageView à toi de voir si tu peux l'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
     
    ImageView refresh = (ImageView) findViewById (R.id.refresh);
    // On crée une animation
    RotateAnimation anim = new RotateAnimation (0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
    anim.setInterpolator (new LinearInterpolator ());
    anim.setDuration (1000);
    anim.setFillEnabled (true);
    anim.setRepeatCount (Animation.INFINITE);
    anim.setFillAfter (true);
    refresh.startAnimation (anim);
     
    // On arrête l'annimation une fois que le traitement est fait
    final Runnable finish = new Runnable ()
    {
    	@Override
    	public void run ()
    	{
    		// TODO : Do something when finish....
    		refresh.clearAnimation ();
    		refresh.setImageDrawable (global.getResources ().getDrawable (R.drawable.btn_refresh));
    	}
    };
    // Permet d'appeler le Runnable dans le thread
    final Handler uiThreadCallback = new Handler ();
     
    // On exécute le traitement dans un Thread 
    new Thread ()
    {
    	@Override
    	public void run ()
    	{
    		// TODO : Do something when ImageView turn...
    		uiThreadCallback.post (finish);
    	}
    }.start ();

    Voila

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

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Par défaut
    Merci!

    Bon je suis presque à la solution, manque plus qu'à arrêter l'image qui tourne et c'est gagné!

  4. #4
    Rédacteur
    Avatar de David55
    Homme Profil pro
    Ingénieur informatique
    Inscrit en
    Août 2010
    Messages
    1 542
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2010
    Messages : 1 542
    Par défaut
    Ba c'est dans mon code!
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    refresh.clearAnimation ();
    refresh.setImageDrawable (global.getResources ().getDrawable (R.drawable.btn_refresh));

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

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Par défaut
    Oui c'est vrai, en fait j'avais fait une erreur, je n'arrivais pas à actualiser la liste après avoir fait tourner la flèche, alors forcément elle tournait sans fin...

  6. #6
    Rédacteur
    Avatar de David55
    Homme Profil pro
    Ingénieur informatique
    Inscrit en
    Août 2010
    Messages
    1 542
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2010
    Messages : 1 542
    Par défaut
    C'est donc résolu?

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

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Par défaut
    On va dire que j'ai un problème qui persiste...

    J'hésite à faire un nouveau sujet.

    Lorsque je rafraîchi mon fragment, la listView se dédouble.

    De plus une flèche reste immobile durant que l'autre tourne par dessus.

    Voici la réaction lords du click sur la flèche:

    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
    public boolean onOptionsItemSelected(MenuItem item){
    	 	mi = item;
     		String str ="";
     
     		if(numFrag == 1)
     			str = "Tag A";
     		else if(numFrag == 2)
     			str = "Tag B";
     
     
     
     		if(numFrag == 0 || numFrag == 1 || numFrag == 2){
     
     			rotation(item);
     
    	 		Fragment currentFragment = getFragmentManager().findFragmentByTag(str);
    	 		FragmentTransaction fragTransaction = getFragmentManager().beginTransaction();
    	 	        fragTransaction.detach(currentFragment);
    	 	        fragTransaction.attach(currentFragment);
    	 	        fragTransaction.commit();
     
     		}
     
     
     		return true;
     	}

    Qu'en pensez-vous? (A mon avis mon fragment est mal rafraichi... Mais je ne sais pas comment pallier à ce problème)

  8. #8
    Rédacteur
    Avatar de David55
    Homme Profil pro
    Ingénieur informatique
    Inscrit en
    Août 2010
    Messages
    1 542
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2010
    Messages : 1 542
    Par défaut
    euh... pourquoi tu rafraîchis le fragment et pas la liste directement?

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

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Par défaut
    Je croyais que dans la classe Fragment il n'y avait pas de méthode onOptionsItemSelected() Je viens de voir la doc et elle y est, bon c'est repartit pour coder! je vous tiens au courant.

    Excusez-moi, c'est ma première "vrai" appli sous android

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

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Par défaut
    Bon j'ai toujours le problème de la liste qui se dédouble à chaque chargements. Je me suis dis que ça viens des threads...

    Sinon j'ai fais la réaction au click dans mon fragment:

    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
    @Override
    		public boolean onOptionsItemSelected(MenuItem item){
     
    			LayoutInflater inflater = (LayoutInflater) getActivity().getApplication().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			ImageView iv = (ImageView) inflater.inflate(R.layout.refresh_action,null);
     
    			Animation rotation = AnimationUtils.loadAnimation(getActivity().getApplication(),R.anim.refresh_rotate);
    			rotation.setRepeatCount(Animation.INFINITE);
    			iv.startAnimation(rotation);
     
    			item.setActionView(iv);
     
    			listView.setAdapter(null);
     
    			creation();//créaction de listview et des items qu'elle contient
     
     
    			iv.clearAnimation ();
    			iv.setImageDrawable (getActivity().getBaseContext().getResources ().getDrawable (R.drawable.ic_action_av_replay));
     
     
    			Log.d("d","Chargement reussi");
     
    			return true;
    		}



    Et si vous le souhaitez, voici ma classe entière:

    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
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    package com.android.rss;
     
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.HashMap;
     
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
     
    import android.app.Activity;
    import android.app.Fragment;
    import android.content.Context;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.os.Bundle;
    import android.os.StrictMode;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.view.WindowManager;
    import android.view.animation.Animation;
    import android.view.animation.AnimationUtils;
    import android.view.inputmethod.InputMethodManager;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.ListAdapter;
    import android.widget.SimpleAdapter;
    import android.widget.ListView;
    import android.widget.TextView;
     
     
     
    /**Premier onglet de l'application, affiche des flux rss*/
    public class MyFragmentA extends Fragment{
     
    	String value = "";
    	/** URL du flux RSS il est défini plus tard */
    	String str;
    	/**URL utilisé pour définir les adresses des images*/
    	String urlImg;
     
     
    	/** Permet de garder chaque descriptions pour les insérer dans l'article lors du click sur un item de la ListView */
    	ArrayList<String> arrayDescription;
    	/** Permet de garder l'URL de chaque image pour les insérer dans l'article lors du click sur un item de la ListView */
    	ArrayList<String> arrayImage;
    	/** Permet de garder chaque titre pour les insérer dans l'article lors du click sur un item de la ListView */
    	ArrayList<String> arrayTitre;
     
    	/** Correspond au fragment sur le quel on est, ici le fragment A */
    	View myFragmentView;
     
    	/** La listView affichant les articles */
    	ListView listView;
     
    	/** Un XMLParser */
    	XMLParser file;
     
    	/** Un Document */
    	Document doc;
     
    	ListAdapter mSchedule;
     
    	//Création de la ArrayList qui nous permettra de remplir la listView
    	ArrayList<HashMap<String, Object>> listData = new ArrayList<HashMap<String, Object>>();
     
    	//On déclare la HashMap qui contiendra les informations pour un item
    	HashMap<String, Object> map;
     
     
    	@Override
    	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
     
    		getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
     
    		Activity activity123 = getActivity();
     
    		if(activity123 instanceof MainActivity) {
    		    ((MainActivity) activity123).setNumFrag(1);
    		}
     
    		this.setHasOptionsMenu(true);
    		//Initialisation du fragmentView
    		myFragmentView = inflater.inflate(R.layout.fragment_a, container, false);
     
     
    		//initialisation des Arraylist contenant les informations pour les articles	  
    		arrayDescription = new ArrayList<String>();
    		arrayImage = new ArrayList<String>();
    		arrayTitre = new ArrayList<String>();
     
     
     
    		InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    		imm.hideSoftInputFromWindow(myFragmentView.findViewById(R.id.txt).getWindowToken(), 0);
     
     
     
    		creation();	  
     
     
    		return myFragmentView;
     
    		}
     
     
    	public void creation(){
     
     
    		//Nouveau thread afin de réaliser une requête HTTP
    		new Thread (new Runnable(){
     
    			public void run(){
     
    				str = httpRequest("http://tempsreel.nouvelobs.com/rss.xml");
    				TextView text = (TextView)myFragmentView.findViewById(R.id.txt);
    				/*http://rss.lemonde.fr/c/205/f/3050/index.rss
    				 *http://tempsreel.nouvelobs.com/rss.xml*/
     
     
    				text.post(new Runnable(){
     
    					public void run(){
    						//Méthode qui réalisera la liste contenant les flux RSS
    						setList(str);
    					}
     
    				});
     
    			}
     
    		}).start();
     
    	}
     
     
     
    		/** Méthode qui réalise une requête HTTP à partir d'une adresse
                     * @param L'adresse du flux rss
                     * @return Un fichier XML avec toute les informations qu'il contient pour afficher la listeView et faire les articles */ 
    		public String httpRequest (String adress){
    			String answer = "", temp = "";
     
    			try{
     
    				URL url = new URL(adress);
    				HttpURLConnection con = (HttpURLConnection) url.openConnection();
    				InputStream in = con.getInputStream();
    				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
     
    				while ((temp = reader.readLine()) != null){
    					answer = answer + temp;
    				}
     
    				reader.close();
     
    			}catch (Exception e){}
     
    			return answer;
    		}
     
     
     
    		/** Méthode qui affiche la ListView
                     * @param Le lien du flux rss*/
    		public void setList(String str){
     
    			file = new XMLParser();
    			doc = file.getDomElement(str);
    			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    			StrictMode.setThreadPolicy(policy);
     
     
    			listData = this.afficherList();
     
     
    			listView = (ListView)myFragmentView.findViewById(R.id.list2);
    			mSchedule = new SimpleAdapter (getActivity().getBaseContext(), listData, R.layout.affichageitem,new String[] {"image", "titre"}, new int[] {R.id.img, R.id.titre});
     
    			Activity activity123 = getActivity();
     
    			if(activity123 instanceof MainActivity) {
    			    ((MainActivity) activity123).setAdapter(mSchedule);
    			}
     
     
    			((SimpleAdapter) mSchedule).setViewBinder(new MyViewBinder());	
     
    			listView.setAdapter(mSchedule);
     
     
    			//Reaction aux clicks sur les items de la ListView
    			listView.setOnItemClickListener(new OnItemClickListener() {
     
    				public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
     
    					Intent myIntent[] = new Intent[arrayTitre.size()];
    					for(int i = 0;i < arrayTitre.size(); i++){
     
    						if(position == i){
     
    							//code specific to first list item    
    							myIntent[i] = new Intent(view.getContext(), Article.class);
     
    							//Passage de paramètres à la nouvelle activité
    							myIntent[i].putExtra("str",value);
    							myIntent[i].putExtra("image",arrayImage.get(i));
    							myIntent[i].putExtra("description",arrayDescription.get(i));
    							myIntent[i].putExtra("titre",arrayTitre.get(i));
    							startActivityForResult(myIntent[i], 0);
    						}
     
     
    					}
     
     
    				}
     
    			});
     
    			mSchedule = null;
     
     
    		}
     
    		@Override
    		public boolean onOptionsItemSelected(MenuItem item){
     
    			LayoutInflater inflater = (LayoutInflater) getActivity().getApplication().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			ImageView iv = (ImageView) inflater.inflate(R.layout.refresh_action,null);
     
    			Animation rotation = AnimationUtils.loadAnimation(getActivity().getApplication(),R.anim.refresh_rotate);
    			rotation.setRepeatCount(Animation.INFINITE);
    			iv.startAnimation(rotation);
     
    			item.setActionView(iv);
     
    			listView.setAdapter(null);
     
    			creation();//créaction de listview et des items qu'elle contient
     
     
    			iv.clearAnimation ();
    			iv.setImageDrawable (getActivity().getBaseContext().getResources ().getDrawable (R.drawable.ic_action_av_replay));
     
     
    			Log.d("d","Chargement reussi");
     
    			return true;
    		}
     
    		public void rotation(MenuItem item){
     
    	 		LayoutInflater inflater = (LayoutInflater) getActivity().getApplication().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			ImageView iv = (ImageView) inflater.inflate(R.layout.refresh_action,null);
     
    			Animation rotation = AnimationUtils.loadAnimation(getActivity().getApplication(),R.anim.refresh_rotate);
    			rotation.setRepeatCount(Animation.INFINITE);
    			iv.startAnimation(rotation);
     
    			item.setActionView(iv);
     
     
     
    	 	}
     
    		/** Méthode qui récupère les informations du fichier XML, un arraylist 
                     * récupère chaque informations comme le titre, la description etc...
                     * @return Les données qui serviront pour la mise en place de la listView*/  
    		public ArrayList<HashMap<String, Object>> afficherList(){
     
    			for(int i=2;i<doc.getElementsByTagName("title").getLength()-1;i++){
     
    				try{
     
    					map = new HashMap<String, Object>();
     
    					Element e = (Element) doc.getElementsByTagName("title").item(i);
    					String id = file.getElementValue(e);
    					arrayTitre.add(id);
    					map.put("titre", id);
     
    					Element elemDescription = (Element) doc.getElementsByTagName("description").item(i - 1);
    					String idDescription = file.getElementValue(elemDescription);
    					arrayDescription.add(idDescription);
     
     
    					Element elemImage = (Element) doc.getElementsByTagName("enclosure").item(i - 2);
    					String idImage = elemImage.getAttribute("url");
    					arrayImage.add(idImage);
    					Bitmap bimage2 = getBitmapFromURL(arrayImage.get(i - 2));
     
     
    					/*Réalise une condition pour savoir si le bitmap retourné est null, si oui 
    					l'image affiché dans l'élément de la listView correspond au logo de l'appplication*/
    					if (bimage2 != null)
    						map.put("image", bimage2);
     
    					else
    						map.put("image", String.valueOf(R.drawable.ic_launcher));
     
     
    					listData.add(map);
     
     
     
    				}catch(NullPointerException e){} 
    			}
     
     
    			return listData;
    		}
     
     
    		/** Méthode qui récupère une image à partir d'une URL
                     * @param L'URL de l'image
                     * @return Un Bitmap correspondant à l'image de l'URL */  
    		public Bitmap getBitmapFromURL(String src) {
     
    			ImageLoader imageLoader = new ImageLoader(getActivity().getBaseContext());
    			Bitmap myBitmap = imageLoader.getBitmap(src);
     
    			return myBitmap;
     
    		}
     
    }

    Qu'en pensez-vous? où m'y suis-je mal pris?

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

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Par défaut
    J'ai une première source de réponse, ma listview se dédoublait car j'avais oublié de faire un clear() sur mon arraylist! (listData).

    Bizarrement ma flèche ne commence même pas à tourner, mais si je ne met rien pour l'arrêter elle tourne. je trouve ça vraiment bizarre.

Discussions similaires

  1. Faire tourner un Gif une seule fois.
    Par Yutsuki dans le forum AWT/Swing
    Réponses: 0
    Dernier message: 03/04/2014, 08h55
  2. [Linux] Faire tourner, sur Linux, une application créée par un Qt Windows
    Par Devour dans le forum Plateformes
    Réponses: 5
    Dernier message: 02/05/2013, 17h00
  3. faire tourner un script à une heure donnée
    Par nebil dans le forum Langage
    Réponses: 2
    Dernier message: 03/07/2006, 12h30
  4. Faire tourner une Application en Taches de fond
    Par ArkAng3 dans le forum MFC
    Réponses: 3
    Dernier message: 26/08/2005, 14h06

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