How to close the current fragment by using Button like the back button?

前端 未结 13 870
失恋的感觉
失恋的感觉 2020-12-07 14:02

I have try to close the current fragment by using Imagebutton.

I am in Fragment-A and it will turn to the Fragment-B when I click the button.

And when I clic

相关标签:
13条回答
  • 2020-12-07 14:32
    Button ok= view.findViewById(R.id.btSettingOK);
    Fragment me=this;
    ok.setOnClickListener( new View.OnClickListener(){
        public void onClick(View v){
         getActivity().getFragmentManager().beginTransaction().remove(me).commit();
        }
    });
    
    0 讨论(0)
  • 2020-12-07 14:35

    getActivity().onBackPressed does the all you need. It automatically calls the onBackPressed method in parent activity.

    0 讨论(0)
  • 2020-12-07 14:37

    Try this one

    getActivity().finish();
    
    0 讨论(0)
  • 2020-12-07 14:38

    If you need to handle the action more specifically with the back button you can use the following method:

    view.setFocusableInTouchMode(true);
    view.requestFocus();
    view.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if( keyCode == KeyEvent.KEYCODE_BACK )
            {
                onCloseFragment();
                return true;
            } else {
                return false;
            }
        }
    });
    
    0 讨论(0)
  • 2020-12-07 14:39

    Try this:

    ft.addToBackStack(null);   // ft is FragmentTransaction
    

    So, when you press back-key, the current activity (which holds multiple fragments) will load previous fragment rather than finishing itself.

    0 讨论(0)
  • 2020-12-07 14:45

    Try this:

    public void removeFragment(Fragment fragment){
        android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
        android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    
        fragmentTransaction.remove(fragment);
        fragmentTransaction.commit();
    }
    
    0 讨论(0)
提交回复
热议问题