0

i have a problem with my web view in fragment that every time press back lead to home page can you help me to make back button goes to previous page .

my fragment jave file includes:-

package com.example.catalogmavbar.ui.cat;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.fragment.app.Fragment;

import com.example.catalogmavbar.R;

public class CatFragment extends Fragment {

    public CatViewModel catViewModel;
    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cat, container, false);
        WebView webView = (WebView)view.findViewById(R.id.webviewncat);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("http://www.catalogmasr.com/categories");
        return view ;


    }


}

  • https://stackoverflow.com/a/6077173/7804719 Try this. – Jaydip Kalkani Nov 28 '19 at 02:30
  • Possible duplicate of [How to go back to previous page if back button is pressed in WebView?](https://stackoverflow.com/questions/6077141/how-to-go-back-to-previous-page-if-back-button-is-pressed-in-webview) – Duy Khanh Nguyen Nov 28 '19 at 02:35

1 Answers1

0

You can make a function in fragment to control webview.goBack() that called by onBackPressed() in activity.

Example

in Fragment

CatFragment {
    ...
    public boolean onBackPressedHandled(){
        if (webview.canGoBack()) {
            webview.goBack();
            return true;
        }
        return false;
    }
}

in Activity:

Activity {
    ...
    public void onBackPressed() {
        if (!catFragment.onBackpressedHandled()) {
            super.onBackPressed();
        }
    }
}
Hababa
  • 551
  • 5
  • 8
  • Please help me to where exactly to add because its keep give me redlines and app crashes in debug – Mahmoud Mahmad Nov 28 '19 at 02:59
  • `1.`make a public method onBackPressedHold() for your catFragment. `2.` override onBackpressed() in your Activity which hold the catFragment. `3.`call `1.` method from `2.` – Hababa Nov 28 '19 at 10:29