Black
Black

Reputation: 20322

WebView - only show back button if back history exists

I developed a simple webview app. I added a button which should act as the back button, so users can navigate back one page.

The button is initially hidden and should only show if a back history exists. How can I realise this?

The code is simple:

backButton = findViewById(R.id.backButton);
backButton.setEnabled(blizzView.canGoBack());

but where do I have to call this? How is the "some site loaded" event called?

Update:

I tried to apply @Murats answer, but nothing happens:

private WebView blizzView;  // my webview
private Button backButton;

public void onPageFinished(WebView view, String url)
{
    backButton = findViewById(R.id.backButton);
    backButton.setEnabled(blizzView.canGoBack());

    if (blizzView.canGoBack()) {
        backButton.setVisibility(View.VISIBLE);
    } else {
        backButton.setVisibility(View.INVISIBLE);
    }

}

Upvotes: 0

Views: 341

Answers (2)

Black
Black

Reputation: 20322

It works like this:

blizzView.setWebViewClient(new WebViewClient() {      //
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        backButton = findViewById(R.id.backButton);
        backButton.setEnabled(blizzView.canGoBack());

        if (blizzView.canGoBack()) {
            backButton.setVisibility(View.VISIBLE);
        } else {
            backButton.setVisibility(View.INVISIBLE);
        }

    }
});

Upvotes: 0

Murat Karagöz
Murat Karagöz

Reputation: 37604

You can use WebView#canGoBack to find out if there is a backstack. You can check for that after the page is loaded e.g. in WebViewClient#onPageFinished

Upvotes: 2

Related Questions