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
Just override onBackPressed() methid of your Activity
You can begin by overriding the back button press in your MainActivity
@Override
public void onBackPressed() {
//super.onBackPressed()
//handle the press here to switch fragments
}
In your activity override on backpressed:
@Override
public void onBackPressed() {
switch (mViewPager.getCurrentItem()) {
case 0:
if (!webViewGoBack(0)) {
//do something if webview cannot go back
}
break;
case 1:
break;
default:
}
}
public boolean webViewGoBack(int num) {
SectionsPagerAdapter adapter = ((SectionsPagerAdapter)mViewPager.getAdapter());
Fragment f = (Fragment )adapter.getFragment(num);
if (f!= null) {
return f.webViewGoBack();
}
return false;
}
f.webViewGoBack() the method in you fragment:
public boolean WebViewGoBack() {
if(webView.canGoBack()){
webView.goBack();
return true;
}
return false; //webview cannot go back, so use the method of the BackButton
}
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
First first_act = new First();
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
@Override
public void onBackPressed() {
}