Question

I have an Actionbar app with fragments and a TabFragment extends Fragment class, where I customize the functionality of my fragments.

I want to be able to control what the back button does.

@Overriding onBackPressed() 

won't work because I am not in an Activity, nor will

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
       //my code here
    }
    return super.onKeyDown(keyCode, event);
}

My goal is to hide some specific Views when I press back based on true/false value of a boolean variable. Any suggestions on how I might be able to manipulate this functionality? Thanks!

a busy cat

Was it helpful?

Solution

I had the same problem as you, but I realized that you had to deal with the back button in the activity where you are running your fragments from. You need to override the onBackPressed() in the activity code, not inside the fragment code. Then you can check to see which fragment is visible and do what you want accordingly. This code is in my activity:

@Override
public void onBackPressed()
{
    try
    {
        final LiveWorkFragment liveFragment = (LiveWorkFragment)getFragmentManager().findFragmentByTag("live_work");//LiveWorkFragment is a fragment
        final NonLiveWorkFragment nonLiveFragment = (NonLiveWorkFragment)getFragmentManager().findFragmentByTag("non_live");//NonLiveWorkFragment is a fragment
        final SignatureFragment signatureFragment = (SignatureFragment)getFragmentManager().findFragmentByTag("signature");//this is a Fragment too

        if(liveFragment == null && nonLiveFragment == null && signatureFragment == null)
        {
            super.onBackPressed();
        }
        if(liveFragment != null)
        {
            if (liveFragment.isVisible())
            {
                //do what you want
            }
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top