2017-05-25 1 views
0

J'ai créé un fragment qui affiche gridview et quand on clique sur un élément de grille, il est lu sur un autre fragment. Mais lorsque j'appuie sur le bouton de retour physique, l'application se referme au lieu de revenir au fragment précédent (c'est-à-dire le fragment contenant la grille). Comment puis-je resoudre ceci?Aller au fragment précédent en appuyant sur le bouton retour physique

+0

se réfèrent https://stackoverflow.com/questions/7992216/android-fragment-handle-back-button-press – sasikumar

+0

double possible de [Comment mettre en œuvre onBackPressed () dans Fragments?] (https://stackoverflow.com/questions/5448653/how-to-implement-onbackpressed-in-fragments) – thepoosh

Répondre

1

essayez celui-ci

@Override 
public void onBackPressed() { 
    if (getFragmentManager().getBackStackEntryCount() > 0){ 
     getFragmentManager().popBackStack(); 
    } else { 
     super.onBackPressed(); 
    } 
} 
+0

merci. ça a marché. –

0
'addToBackStack' is used for moving back to previous fragment, you can use a common Function 

    in your Main activity for changing fragment. 




public void change_fragment(Fragment fragment, int frame) { 


    FragmentManager manager = getSupportFragmentManager(); 
    FragmentTransaction trans = manager.beginTransaction(); 
    //trans.setCustomAnimations(R.anim.enterfrom_left, R.anim.exit_to_right,R.anim.enterfrom_left, R.anim.exit_to_right); 
    trans.replace(frame, fragment); 
    trans.addToBackStack("hai" + frame); 
    trans.commit(); 


    } 



    you can call it from Main activity like this 

    change_fragment(new Frag(),R.id.fl_main_frag_container); 



    you can call it from another fragment like this 

    ((MainActivity)getContext()).change_fragment(new Frag(), R.id.fl_main_frag_container);