how to go back to previous fragment on pressing manually back button of individual fragment?

后端 未结 10 1421
悲&欢浪女
悲&欢浪女 2020-11-27 04:49

I have only one activity and multiple fragments in my application.

Two main fragment A(left) and B(right).



        
相关标签:
10条回答
  • 2020-11-27 05:44
    @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){
    
                    // replace your fragment here
    
                    return true;
    
                }
    
                return false;
            }
        });
    }
    

    // Happy Coding

    0 讨论(0)
  • 2020-11-27 05:46

    You can handle it by adding tag in the backStack. Check my answer here :

    https://stackoverflow.com/a/19477957/1572408

    hope it helps

    0 讨论(0)
  • 2020-11-27 05:48

    Try this, Its Work for me.

    public void onBackPressed() {
        if (mainLayout.isMenuShown()) {
            mainLayout.toggleMenu();
        } else {
            FragmentManager fm = getSupportFragmentManager();
            Log.print("back stack entry", fm.getBackStackEntryCount() + "");
    
            if (fm.getBackStackEntryCount() > 1) {
                fm.popBackStack();
                // super.onBackPressed();
                // return;
            } else {
                if (doubleBackToExitPressedOnce) {
                    fm.popBackStack();
                    super.onBackPressed();
                    return;
                }
    
                this.doubleBackToExitPressedOnce = true;
                Toast.makeText(this, "Press one more time to exit",
                        Toast.LENGTH_SHORT).show();
    
                new Handler().postDelayed(new Runnable() {
    
                    @Override
                    public void run() {
    
                        doubleBackToExitPressedOnce = false;
                    }
                }, 3000);
    
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-27 05:48

    If you press back image you have to create method first like this

    private void Backpresses() {
        getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.contant_main, new Home()).commit();
    }
    

    then you have to call like this when you press back image..

     back.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                       Backpresses();
    
                    }
                });
    

    It work fine for me.

    0 讨论(0)
提交回复
热议问题