Search code examples
androidfragmentonbackpressed

Using BackButton in Fragments Android


I'd like to use the BackButton in Fragments. I'm using this code to handle backbutton:

 @Override
public void onResume() {
    super.onResume();

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){

                if (idozit.num > 0) {
                    if (!pmenu.pauseopen) {
                        pmenu.BeingPaused(idozit.idozitomegy,nextlevel,0);
                    } else {
                        pmenu.continuegame();
                    }
                }
                if (idozit.num == 0) {
                    idozit.numnull(db);
                }
               //Toast.makeText(getActivity(), "hello1", Toast.LENGTH_SHORT).show();
                return true;
            }
            return false;
        }
    });
}

When I click on BackButton this code works fine BUT if click on the BackButton again the app calls the onBackPressed method from MainActivity. I don't know why but if I'm using only a Toast or Log.d something like that in the onKey method then I'm able to click it again. I'd like to say that pmenu is a simple class which is only stops music,make things gone etc. It's seems like somehow I always stuck in that class . Have you any idea what am I doing wrong?


Solution

  • A cleaner solution is to make an Interface implemented by every fragment with a method called onBackPressed() like this:

    public interface FragmentInterface {
        void onBackPressed();
    }
    

    Then, you override the onBackPressed in yout activity calling your current fragment's onBackPressed (I'm assuming that you have a method to get your currentFragment)

    @Override
    public void onBackPressed(){
        FragmentInterface currentfragment = getCurrentFragment();
        currentfragment.onBackPressed();
    }
    

    Of course, in your fragment, implemented method should look like this:

    @Override
    public void onBackPressed() {
        if (idozit.num > 0) {
            if (!pmenu.pauseopen) {
                pmenu.BeingPaused(idozit.idozitomegy,nextlevel,0);
            } else {
                pmenu.continuegame();
            }
        }
        if (idozit.num == 0) {
            idozit.numnull(db);
        }
        //Toast.makeText(getActivity(), "hello1", Toast.LENGTH_SHORT).show();
    }