Question

I want to have a button press display a web page, I use the standard approach with a WebViewClient and WebChromClient like so:

final Button revsButton = (Button) this.findViewById(R.id.buttonReviews);
revsButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        wb.setWebViewClient(new ShareWebViewClient());  
        wb.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                activity.setTitle("Loading Reviews...");
                activity.setProgress(progress * 100); 
                if(progress == 100)
                    activity.setTitle(R.string.app_name);
            }
        });
        wb.getSettings().setJavaScriptEnabled(true);  
        wb.loadUrl(revString );  
        setContentView(wb);                         
    }
}); 


private class ShareWebViewClient extends WebViewClient {  
    public boolean shouldOverrideUrlLoading(WebView view, String url) {   
        view.loadUrl(url);   
        return true;  
    } 
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
          Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
      }
} 

This is all working great, the thing is when I press the Back button it exits my Activity entirely and returns to the previous page. What I really want the back button to do is to close the WebViewClient and return to the dispaly with the button on it. This is what I tried to do so far which half worked -- it didn't leave the activity, but the activity page was just a blank screen instead of showing the controls that should be on there.

@Override
public void onBackPressed() {
    if (wb.getVisibility() == View.VISIBLE) {
        wb.setVisibility(View.INVISIBLE);
    } else {
        finish();
    }
}
Was it helpful?

Solution

I suppose this happens because you're using WebViewClient rather than launching browser using standard:

Uri uri=Uri.parse(urlString);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
activity.startActivity(intent);

In this case BACK button would close browser activity and you'll get back your primary activity.

In your case I would propose in onBackPressed() - restore your original content selecting

setContentView(my_original_layout);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top