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

AndroidAndroid FragmentsActivity Finish

Android Problem Overview


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 click the button at Fragment-B , it will turn to the Fragment-C and close the Fragment-B.

If I click the back button at Fragment-C , it will back to the Fragment-A.

The code I have try is like the following

camera_album = (ImageButton) view.findViewById(R.id.camera_album);

camera_album.setOnClickListener(new Button.OnClickListener() {
	@Override
	public void onClick(View v) {
	
	                closefragment();
		Fragment fragment = FileBrowserFragment.newInstance(null, null, null) ;
		MainActivity.addFragment(LocalFileBrowserFragment.this, fragment) ;
	
	
	}
});

private void closefragment() {
	getActivity().getFragmentManager().beginTransaction().remove(this).commit();
}

When I click the back button at fragment-B , it turn to the Fragment-C.

But when I click the back button on Fragment-C , it doesn't back to the Fragment-A. It back to the empty background. If I want to back to Fragment-A , I have to click the back button once again.

SO , it seem doesn't close the current fragment complete.

How to finish the current fragment like the back button of Android ?

Android Solutions


Solution 1 - Android

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

to

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

And it can close the fragment.

Solution 2 - Android

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.

Solution 3 - Android

For those who need to figure out simple way

Try getActivity().onBackPressed();

Solution 4 - Android

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

Solution 5 - Android

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();
}

Solution 6 - Android

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()
    }
}

Solution 7 - Android

simply close the activity

getActivity().onBackPressed();

Solution 8 - Android

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.

Solution 9 - Android

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();
	}
});

Solution 10 - Android

You can try this logic because it is worked for me.

frag_profile profile_fragment = new frag_profile();

boolean flag = false;
@SuppressLint("ResourceType")
public void profile_Frag(){
    if (flag == false) {
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        manager.getBackStackEntryCount();
        transaction.setCustomAnimations(R.anim.transition_anim0, R.anim.transition_anim1);
        transaction.replace(R.id.parentPanel, profile_fragment, "FirstFragment");
        transaction.commit();
        flag = true;
    }

}

@Override
public void onBackPressed() {
    if (flag == true) {
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        manager.getBackStackEntryCount();
        transaction.remove(profile_fragment);
        transaction.commit();
        flag = false;
    }
    else super.onBackPressed();
}

Solution 11 - Android

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;
	    }
	}
});

Solution 12 - Android

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;
    }

Solution 13 - Android

For remove current fragment B and navigate to stack back (other fragment A):

private fun navigateToBackStack() {
    requireActivity().supportFragmentManager
        .beginTransaction()
        .remove(this)
        .commit()
    requireActivity().supportFragmentManager.popBackStack()
}

GL

Solution 14 - Android

if you need in 2020

    Objects.requireNonNull(getActivity()).onBackPressed();

Solution 15 - Android

Try this one

getActivity().finish();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWunView Question on Stackoverflow
Solution 1 - AndroidWunView Answer on Stackoverflow
Solution 2 - AndroidS.D.View Answer on Stackoverflow
Solution 3 - AndroidViswanath LekshmananView Answer on Stackoverflow
Solution 4 - AndroidFarruh HabibullaevView Answer on Stackoverflow
Solution 5 - Androiduser3773246View Answer on Stackoverflow
Solution 6 - AndroidAbdul RehmanView Answer on Stackoverflow
Solution 7 - Androidnafees ahmedView Answer on Stackoverflow
Solution 8 - AndroidShailendra MaddaView Answer on Stackoverflow
Solution 9 - AndroidBruno L.View Answer on Stackoverflow
Solution 10 - AndroidRahul RathoreView Answer on Stackoverflow
Solution 11 - Androiduser6683868View Answer on Stackoverflow
Solution 12 - AndroidIlmardView Answer on Stackoverflow
Solution 13 - AndroidBraian CoronelView Answer on Stackoverflow
Solution 14 - AndroidCroidView Answer on Stackoverflow
Solution 15 - AndroidKaran ChunaraView Answer on Stackoverflow