Search code examples
androidandroid-actionbarandroid-webviewwebviewclient

How to listen to webview url click and enable/disable buttons on actionbar


I'm developing an application in which I'm using webview to load certain websites. I also have customized actionbar on which I have website navigation button. Here is the view how my layout is looking like:

How it looks to me.

When I load website my all three buttons are visible, but I want them to be visible at that time only when user has clicked on some URL, so user easily understand the purpose of those buttons.

I have added all the functionalities to those button. Here is my code:

website_back = (ImageButton) cView.findViewById(R.id.website_back);
website_forward = (ImageButton) cView.findViewById(R.id.website_forward);
website_refresh = (ImageButton) cView.findViewById(R.id.website_refresh);

if (v.getId() == R.id.website_back) {
    webview.goBack();
}
if (v.getId() == R.id.website_forward) {
    webview.goForward();
}
if (v.getId() == R.id.website_refresh) {
    webview.reload();
}

My WebViewClient:

private class HelloWebViewClient extends WebViewClient {

    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        progress.setVisibility(View.VISIBLE);
        super.onPageStarted(view, url, favicon);
    }

    public void onPageFinished(WebView view, String url) {
        progress.setVisibility(View.GONE);
        super.onPageFinished(view, url);
    }

    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        website_back.setImageResource(R.drawable.webview_back);
        view.loadUrl(url);
        return true;
    }
}

How can I only show those buttons when user has clicked on some URL, on the website launched in the webview?

Any kind of help will be appreciated.


Solution

  • You need to attach a WebViewClient to the WebView to listen in on the URLs that are being fetched.

    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(url.equals(mOriginalUrl)){
                //initial url load, ignoring.
            }
            else {
                //url was navigated to - do something
            }
    
            return super.shouldOverrideUrlLoading(view, url);
        }
    
        @Override
        public void onPageFinished(WebView view, String url) {
            //page has finished loading
        }
    });