I am now having an activity containing fragments
[1] , [2] , [3] , [4]
If pressing buttons , [3] , it can be redirected to [4]
I would like to implement the back button as shown follow..
when pressing back at [4] , it return to [3]
when pressing back at [3] , it return to [2]
when pressing back at [1] , the activity finishes();
When it comes to the current implementation, it finish the activity instead of popping up the Fragment. Would you please tell me what I should do or keep in mind ?
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if( keyCode==KeyEvent.KEYCODE_BACK) { finish(); } return super.onKeyDown(keyCode, event); }
addToBackStack. Add this transaction to the back stack. This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack.
This worked for me.
-Add .addToBackStack(null) when you call the new fragment from activity.
FragmentTransaction mFragmentTransaction = getFragmentManager() .beginTransaction(); .... mFragmentTransaction.addToBackStack(null);
-Add onBackPressed() to your activity
@Override public void onBackPressed() { if (getFragmentManager().getBackStackEntryCount() == 0) { this.finish(); } else { getFragmentManager().popBackStack(); } }
Easiest way ever:
onResume():
@Override public void onResume() { super.onResume(); getView().setFocusableInTouchMode(true); getView().requestFocus(); getView().setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) { // handle back button's click listener Toast.makeText(getActivity(), "Back press", Toast.LENGTH_SHORT).show(); return true; } return false; } }); }
Edit 1: If fragment having EditText
.
private EditText editText;
onCreateView():
editText = (EditText) rootView.findViewById(R.id.editText);
onResume():
@Override public void onResume() { super.onResume(); editText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { editText.clearFocus(); } return false; } }); getView().setFocusableInTouchMode(true); getView().requestFocus(); getView().setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) { // handle back button's click listener Toast.makeText(getActivity(), "Back press", Toast.LENGTH_SHORT).show(); return true; } return false; } }); }
Note: It will work if you have EditText in fragment.
Done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With