0

I have a SearchActivity that works, but I want to be able to close it by pressing back. If I do that right now, first the keyboard is gone (which is as I want), but if I press it again I destroy the fragment. Instead, I want to close the search. Because I am in a fragment I can't manage to make a onBackPressed().

Current code:

@Override
    public void onBackPressed() {
        // Only close if the Fragment reference is null.
        if(Ships == null)
        {
            super.onBackPressed();
        }
        else
        {
            Ships.onBackPressed();
        }
    }
newToEverything
  • 309
  • 4
  • 13

2 Answers2

1

If you really need to, you may keep a reference of the Fragment and notify the fragment that onBackPressed() occurred. Although this will give you the result that you want, it is not optimal.

In the Activity

@Override
public void onBackPressed()
{
    // Only close if the Fragment reference is null.
    if(mFragment == null)
    {
        super.onBackPressed();
    }
    else
    {
        mFragment.onBackPressed();
    }
}

In the Fragment

MyFragment extends Fragment
{
     public void onBackPressed()
     {
         // Execute here.
     }
}
Newtron Labs
  • 809
  • 1
  • 5
  • 17
0

Override onBackPressed():

  1. If keyboard is open - let system handle back press event
  2. If SearchView has currently focus - then clear focus
  3. Otherwise let system handle back press event.

     @Override
     public void onBackPressed() {
         final boolean isKeyboardOpen = ...;
         if (isKeyboardOpen) {
             super.onBackPressed();
         } else if (searchView.hasFocus()) {
             searchView.clearFocus();
         } else super.onBackPressed();
     } 
    
Community
  • 1
  • 1
azizbekian
  • 60,783
  • 13
  • 169
  • 249