search

Home  >  Q&A  >  body text

android - Fragment中的WebView如何监听其返回监听事件?

我在Fragment的布局中放置了一个WebView,想监听WebView的返回键,该如何实现?

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
                    webview.goBack();
                    return true;
                }
                return false;
            }
        });
    }

这样监听没用

大家讲道理大家讲道理2772 days ago502

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-04-18 09:07:04

    Fragment 本身是没有 Activity#onBackPressed() 这样的接口的, 所以需要 Activity 主动通知 Fragment :

    public class ActivityA extends Activity {
        ... ...
        
        @Override
        public void onBackPressed() {
            FragmentA fragment = findFragmentA();
            if (fragment.onBackPressed()) {
                return ;
            }
            
            super.onBackPressed();
        }
    }
    
    public class FragmentA extends Fragment {
        public boolean onBackPressed() {
            if (webview.canGoBack()) {
                webview.goBack();
                return true;
            }
            
            return false;
        }
    }
    

    reply
    0
  • Cancelreply