package com.example.fragmentdynamic;


import android.os.Bundle;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
      FragmentManager fragmentManager = getFragmentManager();
      FragmentTransaction fragmentTransaction = 
      		fragmentManager.beginTransaction();  
      Fragment fragment1=
        		(Fragment)fragmentManager.findFragmentById(R.id.fragmentContainer1);
      if (fragment1==null){
    	  fragmentTransaction.add(R.id.fragmentContainer1, new Fragment1());
      }
      
      Fragment fragment2=
      		(Fragment)fragmentManager.findFragmentById(R.id.fragmentContainer2);
      if (fragment2==null){
      	fragmentTransaction.add(R.id.fragmentContainer2, new Fragment2());
      }	
      
    
      // COMPLETE HERE CODE FOR fragment 3
      XXXXXXXXXXXXXXXXXX
      
      fragmentTransaction.commit(); 
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.mymenu, menu);
		return true;
	}
	
	/**
	 * Gestion du clic sur l'ActionBar
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {

		case R.id.item1:
			FragmentManager fragmentManager = getFragmentManager();
    		FragmentTransaction fragmentTransaction = 
    				fragmentManager.beginTransaction(); 
    		Fragment fragmentB=
    	        		(Fragment)fragmentManager.findFragmentById(R.id.fragmentContainer2);

    		if (fragmentB instanceof Fragment2){
    			fragmentTransaction.replace(R.id.fragmentContainer2, new Fragment1() );
        		fragmentTransaction.replace(R.id.fragmentContainer1, new Fragment2());
    		}
    		else{
    			fragmentTransaction.replace(R.id.fragmentContainer2, new Fragment2() );
        		fragmentTransaction.replace(R.id.fragmentContainer1, new Fragment1());
    		}
    		fragmentTransaction.commit();
			Toast.makeText(this, "Fragment permut", Toast.LENGTH_SHORT).show();  
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}
