Search code examples
androidfragmentfragmenttransaction

How to cancel FragmentTransaction commit


I have to give the user an option to capture video in my app but I not want the preview appear (or take a space) when the video is not recording.

Therefore I build a floating preview using FragmentTransaction based on camera2video google example.

My class variables are:

FragmentTransaction fm = null;
Camera2VideoFragment camera2VideoFragment;

And I create an instance and initialize the camera in OnCreate method:

camera2VideoFragment = Camera2VideoFragment.newInstance();
if (null == savedInstanceState) {
    fm = getFragmentManager().beginTransaction()
            .replace(R.id.container, camera2VideoFragment);
}

I want to visibile and hide the preview(fragment) using the menu methods (onOptionsItemSelected):

case R.id.action_captureScreen:
    item.setChecked(!item.isChecked());
    if (item.isChecked())
    {
        fm.commit(); // show the preview - working
        // camera2VideoFragment.captureVideo();  // start capture video
    }
    else
    {
        //camera2VideoFragment.captureVideo();  // stop the video and save to file
        fm.detach(camera2VideoFragment);        // hide the preview - NOT WORKING
    }

I also tried fm.hide(camera2VideoFragment) but it also does not work.

So, the question is, how can I hide/show the preview?


Solution

  • You're confusing some terms. A transaction is only "executed" by the fragment system after you commit it. Before calling commit() nothing happens.

    So you have do execute two different transactions, one for show and a different one for hiding.

    show:

    getFragmentManager().beginTransaction().show(camera2VideoFragment).commit();
    

    hide:

    getFragmentManager().beginTransaction().hide(camera2VideoFragment).commit();