Simone Varletta
Simone Varletta

Reputation: 289

Android WebView back button go back twice

Hello i have a fragment with webview here it is:

public class ListaCanali extends Fragment {

TextView textView;
WebView webView;
ProgressBar progressBar;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v =inflater.inflate(R.layout.lista_canali,container,false);

    //Titolo Fragment
    ((MainActivity) getActivity()).setActionBarTitle("Ultimi Film Pubblicati");

    //FindViewById
    webView = (WebView) v.findViewById(R.id.webview);
    textView = (TextView) v.findViewById(R.id.textView);
    progressBar = (ProgressBar) v.findViewById(R.id.progressBar);

    //Impostazioni WebView
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setLoadsImagesAutomatically(true);
    webView.loadUrl("http://testoetraduzione.org");
    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    webView.getSettings().setAppCacheEnabled(false);
    webView.setWebViewClient(new WebClient());

    //Tasto Indietro
    webView.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
                webView.goBack();
                return true;
            }
            return false;
        }
    });

    return v;
}

Why when i press back button the webview go back twice! Please write me a right code! of course i rate the best

Upvotes: 0

Views: 1673

Answers (2)

Giorgio Antonioli
Giorgio Antonioli

Reputation: 16224

Instead of setOnKeyListeneron WebView, override onKeyDown method of the activity. You have to handle well fragment lifecycle, if not it can bring to a crash.

Get the instance of the fragment in your activity:

// Fragment f = instance of your fragment
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && f != null && f.canGoBack()) {
        f.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

And add these methods in your fragment:

public boolean canGoBack() {
    return webView != null &&webView.canGoBack();
}

public void goBack() {
    if(webView != null) {
       webView.goBack();  
    }  
}

Upvotes: 3

Stone Edge
Stone Edge

Reputation: 62

Correct me if I'm wrong, but you don't even need a keylistener on the back button to go back, because it already is configured to do so! That's why it would go back twice : once by the nature of the button, once because of your actionlistener

Upvotes: 0

Related Questions