Implementing back button in webview fragment

前端 未结 4 790
花落未央
花落未央 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:30

    Just override onBackPressed() methid of your Activity

    0 讨论(0)
  • 2021-01-25 23:31

    You can begin by overriding the back button press in your MainActivity

    @Override
    public void onBackPressed() {
        //super.onBackPressed()
        //handle the press here to switch fragments
    }
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2021-01-25 23:51
    FragmentManager fragmentManager = getSupportFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager
                            .beginTransaction();
                    First first_act = new First();
    
                    fragmentTransaction.replace(R.id.fragment_container,
                            first_act);
                    fragmentTransaction.addToBackStack("first_act");
                    fragmentTransaction.commit();
    

    Add these code in mainactivity , and then use this onbackpressed in fragment

    @Override
      public void onBackPressed() {
    
      }
    
    0 讨论(0)
提交回复
热议问题