cari

Rumah  >  Soal Jawab  >  teks badan

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 hari yang lalu501

membalas semua(1)saya akan balas

  • ringa_lee

    ringa_lee2017-04-18 09:07:04

    Fragment sendiri tidak mempunyai antara muka seperti Activity#onBackPressed(), jadi Activity perlu memaklumkan secara proaktif 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;
        }
    }
    

    balas
    0
  • Batalbalas