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

前端 未结 13 871
失恋的感觉
失恋的感觉 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:49

    From Fragment A, to go to B, replace A with B and use addToBackstack() before commit().

    Now From Fragment B, to go to C, first use popBackStackImmediate(), this will bring back A. Now replace A with C, just like the first transaction.

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

    if you need in 2020

        Objects.requireNonNull(getActivity()).onBackPressed();
    
    0 讨论(0)
  • 2020-12-07 14:52

    I change the code from getActivity().getFragmentManager().beginTransaction().remove(this).commit();

    to

    getActivity().getFragmentManager().popBackStack();
    

    And it can close the fragment.

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

    For those who need to figure out simple way

    Try getActivity().onBackPressed();

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

    In your Fragments onCreateView(...) you can remove a view by calling container.removeView(view);. So if you want to remove the fragment, then view should be the return value of onCreateView,

    for example

        public View onCreateView(...){
            final View view = inflater.inflate(R.layout.your_fragments_layout,container,false);
            //Do something
            finishButton.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v){
                    container.removeView(view);
                }
            });
            return view;
        }
    
    0 讨论(0)
  • 2020-12-07 14:59

    This is a Kotlin way of doing this, I have created button in fragment layout and then set onClickListner in onViewCreated.

    according to @Viswanath-Lekshmanan comment

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) 
    {
         super.onViewCreated(view, savedInstanceState)
    
         btn_FragSP_back.setOnClickListener {
            activity?.onBackPressed()
        }
    }
    
    0 讨论(0)
提交回复
热议问题