Android back button from WebViewClient doesn't return to current Activity
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 wha开发者_如何转开发t 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();
}
}
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);
精彩评论