简体   繁体   中英

Method does not override method from its superclass, Android Fragment with onBackPressed()

So I have a pretty simple webview application and I am trying to implement an onBackPressed() so that when they click the back button, the user goes back to the previous page.

I looked online and it states that I have to add this:

@Override
public void onBackPressed() {
    if (webView.canGoBack()) {
        webView.goBack();
    } else {
        super.onBackPressed();
    }
}

This is the activity that I am trying to add the onBackPressed() on:

public class ForumActivity extends Fragment {
    private WebView webView;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.activity_forum, container, false);
        final WebView webView = (WebView) view.findViewById(R.id.forum_view);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
                return false;
            }

        });

        // mWebView settings...
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAppCacheEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setDomStorageEnabled(true);
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.setScrollbarFadingEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        } else {
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        // Load URL
        webView.loadUrl("link");

        return view;


    }

When I tried adding it initially, this happens . The error it shows is "Method does not override method from its superclass".

What should I do?

This is the activity that I am trying to add the onBackPressed() on:

You're linking the code for a Fragment. Not an Activity. There's a huge difference.
Fragments do not have a callback to intercept back presses.
Activities do.
You've named that class 'ForumActivity', but it is actually a Fragment.

So you'll have to override the method in your Activity, and then link that up with your Fragment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM