0

I have one activity in my app and I have 2 fragments - A and B. In MainActivity layout there is a FrameLayout. From MainActivity I call FragmentManager to load fragment A into FrameLayout. Then, from fragment A I load fragment B into FrameLayout. In my fragment B I implement onBackPressed() and *onKeyDown(int _a, KeyEvent _b)* from MainActivity to make back button work with WebView in fragment B. But it works as if I didn't implement it!

MainActivity interface:

public interface onKeyDownListener {
    public void onBackPressed();

    public boolean onKeyDown(int _a, KeyEvent _b);
}

Fragment B implementation:

 public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
        mWebView.goBack();
        return true;
    }
    return getActivity().onKeyDown(keyCode, event);
}

public void onBackPressed() {

    if (mWebView.isFocused() && mWebView.canGoBack()) {
        mWebView.goBack();
    } else {
        Toast.makeText(getActivity().getApplicationContext(), "This's working!", 50000).show();
        getActivity().onBackPressed();
    }
}

No one of these methods works, back button just close the application.

Egor Gavrilov
  • 25
  • 1
  • 5

1 Answers1

3

The onBackPressed is a function on the activity, not the fragment. You'll have to catch it in the Activity and pass it on to the fragment to process

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • What do you mean? I tried to @Override it but it didn't work too. – Egor Gavrilov Jul 07 '13 at 07:29
  • 1
    Fragments don't have an onBackPressed function. So that's why it isn't being called. Activities have them, not Fragments. @Override not working should have told you that Fragments don't have a function named that, so it wouldn't be called. – Gabe Sechan Jul 07 '13 at 07:30
  • Yes, I know, but I implement these functions from MainActivity. Should I do it in a different way? – Egor Gavrilov Jul 07 '13 at 07:34
  • That's not what you say above- you say above that they're part of your fragment. You look like you have things backwards- you have the fragment expecting to get the back key and calling Activity, it needs to be Activity getting the back key and calling Fragment. – Gabe Sechan Jul 07 '13 at 08:19