Created
January 14, 2016 05:35
-
-
Save erkattak/c674fc4a4b770baf1069 to your computer and use it in GitHub Desktop.
How to override Activity onBackPressed from a Fragment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BaseActivity extends AppCompatActivity { | |
protected OnBackPressedListener onBackPressedListener; | |
public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) { | |
this.onBackPressedListener = onBackPressedListener; | |
} | |
@Override | |
public void onBackPressed() { | |
if (onBackPressedListener != null) { | |
onBackPressedListener.doBack(); | |
} else { | |
super.onBackPressed(); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BaseBackPressedListener implements OnBackPressedListener { | |
private final FragmentActivity activity; | |
public BaseBackPressedListener(FragmentActivity activity) { | |
this.activity = activity; | |
} | |
@Override | |
public void doBack() { | |
if (!activity.getSupportFragmentManager().popBackStackImmediate()) { | |
activity.supportFinishAfterTransition(); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface OnBackPressedListener { | |
void doBack(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class WebViewFragment extends Fragment { | |
@Override | |
public void onCreate(@Nullable Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
configureBackPressedListener(); | |
} | |
public void configureBackPressedListener() { | |
((BaseActivity) getActivity()).setOnBackPressedListener(new BaseBackPressedListener(getActivity()) { | |
@Override | |
public void doBack() { | |
if (mWebView.canGoBack()) { | |
mWebView.goBack(); | |
} else { | |
super.doBack(); | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment