Implementing back button in webview fragment

前端 未结 4 820
花落未央
花落未央 2021-01-25 23:13

I want to implement the back button to my app. I\'m using fragments that each show a different webview. Right now if I press the back button, it closes the app no matter where I

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-25 23:48

    In your activity override on backpressed:

    @Override
        public void onBackPressed() {
            switch (mViewPager.getCurrentItem()) {
            case 0:
                if (!webViewGoBack(0)) {
                        //do something if webview cannot go back
                }
                break;
            case 1:
    
                break;
            default:
    
            }
        }
    
    public boolean webViewGoBack(int num) {
            SectionsPagerAdapter adapter = ((SectionsPagerAdapter)mViewPager.getAdapter());
            Fragment f = (Fragment )adapter.getFragment(num);
            if (f!= null) {
                return f.webViewGoBack();
            }
            return false;
        }
    

    f.webViewGoBack() the method in you fragment:

    public boolean WebViewGoBack() {
    if(webView.canGoBack()){
       webView.goBack();
       return true;
    }
    return false; //webview cannot go back, so use the method of the BackButton
    }
    

提交回复
热议问题