How to Implement Onbackpressed() & Intents in Fragment

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



Leave a reply



Submit