1. 2015 is going to be a great year for Android! Why wait??
    Samsung Galaxy Note 5 | Samsung Galaxy S6 | HTC One M9
  2. New Forum Created: Samsung Gear VR!

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


  1. RED_

    RED_ Well-Known Member

    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!

    Advertisement
    :
  2. jonbonazza

    jonbonazza Well-Known Member

    Have you tried overriding the back button?
  3. RED_

    RED_ Well-Known Member

    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.
  4. RED_

    RED_ Well-Known Member

    I'm currently looking into this, is there any chance you could explain how I would go about overriding the back button? Thanks.
  5. jonbonazza

    jonbonazza Well-Known Member

    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]
  6. RED_

    RED_ Well-Known Member

    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.
Loading...

Share This Page