• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps 5 Fragments - get back button to return to certain Fragment? It closes app at the moment.

RED_

Well-Known Member
Nov 13, 2010
209
8
London
Hey all.

I've set up a horizontal scrolling system to move between 5 different Fragments, at the moment pressing the back button on the phone/tablet will exit the app. This happens on all Fragments.

Can anyone help in getting the back button to move to the first fragment. So Fragment 2, 3 , 4 and 5 will all move to Fragment 1 when the back button is pressed.

I've been looking into Fragment transactions but I can't get them to work, I guess I just don't understand it that well yet. Maybe it's not the correct way.

I have the horizontal scrolling thing set up in the usual way. Each Fragment has it's own Java file, there's a Fragment pager adapter. based within a FragmentActivity.

So can anyone give me some advice on where to go with this?
Appreciate any help!
 
Have you tried overriding the back button?

I haven't. At the moment I have an AlertDialog that asks the user if they want to exit the app. I want the user to be able to get back to Fragment 1 but then when they hit the back button on Fragment 1 the AlertDialog comes up. I don't overriding the back button can achieve this.
 
Upvote 0
Add the following to your activity:
[high]
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
return true;
}
return super.onKeyDown(keyCode, event);
}

private void onBackPressed() {
//Add fragment handling code here
}
[/high]
 
Upvote 0
I'm getting the following error with "OnBackPressed()":

"Cannot reduce the visibility of the inherited method from FragmentActivity"

I'm putting it in my FragmentActivity because that's where all the Fragments are handled with the ViewPager. Each Fragment has it's own java file so it's not a subclass of an Activity.


EDIT: If anyone else finds this I achieved what I wanted by overriding the back button with an if statement. Calling it to set the ViewPager's currentItem to the desired page if it wasn't or call a DialogFragment class that I created which simply contained an AlertDialog.
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones