How to implement onBackPressed() & intents in fragment?
Override onKeyDown instead of onBackPressed. Not necessarily . But this works for me
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
String cameback="CameBack";
intent = new Intent(getActivity(),HomeActivity.class);
intent.putExtra("Comingback", cameback);
startActivity(intent);
return true
}
return false;
}
onBackPressed from Fragment Displays Activity Twice
Why you don't just finish the activity within the fragment to return to the launcher activity?
If you really have to use a intent, try Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
Implement Back Pressed In Android Fragments
You can even try this way
MainActivity.java
@Override
public void onBackPressed() {
if (getFragmentManager() != null && getFragmentManager().getBackStackEntryCount() >= 1) {
String fragmentTag = getFragmentManager().findFragmentById(R.id.frame_container).getTag();
if(fragmentTag.equals(LoginFragment.getTag())){
// show Dialog code
}else{
super.onBackPressed();
}
} else {
super.onBackPressed();
}
}
Add this code in your main activity so that when login fragment is added and you click backpress, then on first if the fragment is added to fragment transaction, then first it finds the fragment and check if its tag is equals to the login fragment tag. Then if both tag matches, then you can show your exit alert dialog.
Android (java): OnBackPress() closes my app when trying to go back from Activity to fragment
According to https://developer.android.com/reference/android/app/Activity, calling onBackPressed finishes the current activity, so it won't be there to return to if called from the launching activity. Removing this call seems to fix the issue seen here.
Related Topics
Gradle Dsl Method Not Found: 'Implementation()'
How to Get Android Avd Name from Adb Device Name
What Is Metadata ? and What Is The Use of It in Android
Android Linearlayout Gradient Background
Eclipse Can't Find Android.Support.V4.Widget.Swiperefreshlayout
How to Add Padding Between Menu Items in Android
How to Know Whether a Recyclerview/Linearlayoutmanager Is Scrolled to Top or Bottom
How to Set The Title Color for The New Toolbar
Supportmapfragment Does Not Support Androidx Fragment
Input Has Different Style on Focus
Android Studio - Processdebugresources Failed
How to Style Appcompat-V7 Toolbar Like Theme.Appcompat.Light.Darkactionbar
Android Studio - Error:Program Type Already Present
Is Fcm (Firebase Cloud Messaging) Token for One Device or for One Account
Android Webview Jellybean -> Should Not Happen: No Rect-Based-Test Nodes Found