Challenge: Using the back button for browser history

Here’s my solution to the challenge.

In PhotoPageFragment.java I have the following code:

public boolean webViewGoBack() {
if (mWebView.canGoBack()) {
mWebView.goBack();
return true;
} else {
return false;
}
}

In PhotoPageActivity.java I have the following code:

@Override
public void onBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (!((PhotoPageFragment) fragment).webViewGoBack()) {
super.onBackPressed();
}
}

In fragement_photo_page.xml I have added the following:

android:id="@+id/fragment_container"

Cheers
Wayne

If you meant by “fragment_container” FrameLayout (which was in initial activity) then there are sometimes null pointer exceptions

Here is a quicker solution, I only changed PhotoPageActivity.java:

    @Override
    public void onBackPressed() {

         WebView webView = findViewById(R.id.web_view);

         if(webView.canGoBack()){
                  webView.goBack();
          }else{
                  super.onBackPressed();
          }

}
1 Like