Fragment With Webview Utilize Harware Back Button To Go To Previous Webpage
Solution 1:
Try overriding onBackPressed() in your Activity
and make it poke the WebView
.
BTW - you could post the piece of Activity
containing the onKeyDown
method as well.
EDIT: Instead of making your methods static
and accessing them the way you do now (BlogFragment.canGoBack()
), first instantiate the fragment:
BlogFragmentblogFragment=newBlogFragment();
blogFragment.canGoBack();
and then just remove the static
from your methods. :)
OPs implementation (with thanks to Klotor) At the head of MainActivity implement:
BlogFragmentblogFragment=newBlogFragment();
Then implement:
public void onBackPressed() {
blogFragment.canGoBack();
if(blogFragment.canGoBack()){
blogFragment.goBack();
}else{
super.onBackPressed();
}
}
The fragment is instantiated outside of the onBackPressed in order to prevent crashing when using a method to navigate between fragments. In this case you need to instantiate a newinstance of the fragment, rather than a whole new fragment.
Solution 2:
** In your Fragment Class Inside OnCreateView put below code**
@OverridepublicViewonCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.your_layout, container, false);
mWebView = (WebView) view.findViewById(R.id.webView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(newMyWebViewClient());
mWebView.loadUrl(expertsUrl);
return view;
}
privateclassMyWebViewClientextendsWebViewClient {
@OverridepublicbooleanshouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
returntrue;
}
}
**In MainActivity class put below code **
@OverridepublicvoidonBackPressed() {
if (WebViewFragment.mWebView!=null) {
if (WebViewFragment.mWebView.canGoBack()) {
WebViewFragment.mWebView.goBack();
}
else {
super.onBackPressed();
}
}
}
Replace WebViewFragment -> with your Fragment mWebView -> with your webview
Hope this will help you!!!!
Post a Comment for "Fragment With Webview Utilize Harware Back Button To Go To Previous Webpage"