0

I want to navigate to another screen when user touch back button. I found a method for this.

    @Override
public void onBackPressed() {
// do something on back.
return;
}

I'm navigating from a fragment.But it is not clear that where I have to use this and how. Please help.

tenten
  • 1,276
  • 2
  • 26
  • 54
  • It is always bad approach to launch another screen on device back button press event. Because back button is made to remove the current Activity from the stack and go back to previous Activity (if any) – naran z Jun 08 '16 at 10:17

2 Answers2

0

Just override the method onBackPressed and navigate to the screen you want to via intents or whichever way you prefer.

@Override
public void onBackPressed() {
    getFragmentManager().beginTransaction.replace(thisfragment,new Fragment).commit();
}

The above code will replace your current fragment with the new fragment to which you want to navigate.

yash sachdeva
  • 637
  • 5
  • 13
0

You'll need to add that method to the Activity class of the screen you're navigating from. Then, in that method, add your intent code to move to your second Activity (let's call that Activity2 below) using startActivity

@Override
public void onBackPressed() {
    Intent intent = new Intent();
    intent.setClass(this, Activity2.class);
    startActivity(intent);
}
Karen Forde
  • 1,117
  • 8
  • 20
  • how use this in a fragment – tenten Jun 08 '16 at 10:41
  • Your original question before editing didn't mention fragments. Your fragment should be attached to an activity, though . If you add this to the activity the fragment is attached to it should give you the desired result. Otherwise, you could try the solution in the accepted answer of this question: http://stackoverflow.com/questions/7992216/android-fragment-handle-back-button-press – Karen Forde Jun 08 '16 at 10:51