Implementing Back Button In Webview Fragment
I want to implement the back button to my app. I'm using fragments that each show a different webview. Right now if I press the back button, it closes the app no matter where I am.
Solution 1:
In your activity override on backpressed:
@OverridepublicvoidonBackPressed() {
switch (mViewPager.getCurrentItem()) {
case0:
if (!webViewGoBack(0)) {
//do something if webview cannot go back
}
break;
case1:
break;
default:
}
}
publicbooleanwebViewGoBack(int num) {
SectionsPagerAdapteradapter= ((SectionsPagerAdapter)mViewPager.getAdapter());
Fragmentf= (Fragment )adapter.getFragment(num);
if (f!= null) {
return f.webViewGoBack();
}
returnfalse;
}
f.webViewGoBack() the method in you fragment:
public boolean WebViewGoBack() {
if(webView.canGoBack()){
webView.goBack();
returntrue;
}
returnfalse; //webview cannot go back, so use the method of the BackButton
}
Solution 2:
Just override onBackPressed() methid of your Activity
Solution 3:
FragmentManagerfragmentManager= getSupportFragmentManager();
FragmentTransactionfragmentTransaction= fragmentManager
.beginTransaction();
Firstfirst_act=newFirst();
fragmentTransaction.replace(R.id.fragment_container,
first_act);
fragmentTransaction.addToBackStack("first_act");
fragmentTransaction.commit();
Add these code in mainactivity , and then use this onbackpressed in fragment
@OverridepublicvoidonBackPressed() {
}
Solution 4:
You can begin by overriding the back button press in your MainActivity
@OverridepublicvoidonBackPressed() {
//super.onBackPressed()//handle the press here to switch fragments
}
Post a Comment for "Implementing Back Button In Webview Fragment"