Implementing back button in webview fragment

梦想的初衷 提交于 2019-12-02 08:18:23

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
}

Just override onBackPressed() methid of your Activity

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() {

  }

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!