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);
}
You can use this .. Worked for me..
It seems as though fragment [3] is not removed from the view when back is pressed so you have to do it manually!
First of all, dont use replace() but instead use remove and add separately. It seems as though replace() doesnt work properly.
The next part to this is overriding the onKeyDown method and remove the current fragment every time the back button is pressed.
if you are using webview inside a fragment than use this in your onCreateView method
and import this class
Make sure to add the following:
in the onKey block of code to avoid the event calling twice.
Ok guys I finally found out a good solution.
In your onCreate() in your activity housing your fragments add a backstack change listener like so:
(Also adding my fragmenManager is declared global) Now every time you change fragment the current fragment String will become the name of the current fragment. Then in the activities onBackPressed() you can control the actions of your back button as so:
I can confirm that this method works for me.
Try this simple solution:
In your activity implement onBackPressed
This will work if you want to pop the top fragment on each back press. Note:- While adding fragment to activity always do add the transaction to back stack for this to work
You can use
getFragmentManager().popBackStack()
in basicFragment
to go back.