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

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 ?

This question is related to android android-fragments activity-finish

The answer is


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

to

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

And it can close the fragment.


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

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

if you need in 2020

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

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


For those who need to figure out simple way

Try getActivity().onBackPressed();


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

Try this one

getActivity().finish();

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

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

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.


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

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-fragments

FragmentActivity to Fragment How to start Fragment from an Activity How to use data-binding with Fragment In android how to set navigation drawer header image and name programmatically in class file? Android Fragment onAttach() deprecated How to convert any Object to String? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments java.lang.IllegalStateException: Fragment not attached to Activity java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

Examples related to activity-finish

How to close the current fragment by using Button like the back button? How to check if activity is in foreground or in visible background? Finish all activities at a time How to press back button in android programmatically? How to finish current activity in Android How to show a dialog to confirm that the user wishes to exit an Android Activity?