0

I am new on android. I cant handle onBackPressed method. I have an Activity class which has four fragment like A,B,C, D. When i lunched Activity by default Fragment A is active and there are link on fragment A to move another Fragment. I want when move another Fragment like B,C,D from Fragment A and pressed Back button it return to Fragment A and if i pressed Back button from Fragment A it show a dialog box. I used onBackPressed() like below

public void onBackPressed() {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            MainActivity.this);

    // set title
    alertDialogBuilder.setTitle("Exit");

    // set dialog message
    AlertDialog.Builder builder = alertDialogBuilder
            .setMessage("Do you really want to exit?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // if this button is clicked, close
                    // current activity
                    MainActivity.this.finish();
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.cancel();
                }
            });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
}

But it work on all fragment and i want to work only Fragment A

6 Answers6

1

You have to handle such requirements in the Activity's onBackPressed only. I usually follow the following approach:

I keep an enum having all the fragments defined and a parameter to track the current fragment:

enum FRAGMENTS{
    fragmentA, fragmentB, fragmentC, fragmentD
}
FRAGMENTS mCurrentFragment;

Now the logic where you change the fragment should have:

public void changeFragment(FRAGMENTS newFragment){
    //Your logic
    mCurrentFragment = newFragment;
}

And finally the logic onBackPressed:

onBackPressed{
     if(mCurrentFragment == FRAGMENTS.fragmentA){
          //Your code here of asking the user if he/she really wants to quit
          super.onBackPressed();
     }else{
          changeFragment(getPreviousFragment(mCurrentFragment));
     }
}

If you dont want to use enum, you can have final int or any other string values to represent different fragments and a mCurrentFragment parameter to keep a track of the currentFragment being shown and then you can easily play with the code in your Activity's onBackPressed method

Let me know if you need more clarification.

avin
  • 459
  • 5
  • 14
1

Add fragment to backStack while replacing

Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

And then override onBackPressed method inside an Activity

Bhargav Thanki
  • 4,924
  • 2
  • 37
  • 43
1

So Here is your answer which you are looking for :)

Method 1

 @Override
 public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {

        // Your stuff here
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

        // set title
        alertDialogBuilder.setTitle("Exit");

        // set dialog message
        AlertDialog.Builder builder = alertDialogBuilder.setMessage("Do you really want to exit?")
                .setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked, close
                        // current activity

                        System.exit(0);
                    }
                }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                    }
                });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();

    }


}

//Tell me if you face any issue

Method 2

or in your case just paste this method in your main activity so you can also achieve it what you want :)
@Override
public void onBackPressed() {
    // TODO Auto-generated method stub

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

    // set title
    alertDialogBuilder.setTitle("Exit");

    // set dialog message
    AlertDialog.Builder builder = alertDialogBuilder.setMessage("Do you really want to exit?").setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // if this button is clicked, close
                    // current activity

                    System.exit(0);
                }
            }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.cancel();
                }
            });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();

}
Kishan Soni
  • 816
  • 1
  • 6
  • 19
  • Do you really think your answer would solve Shailesh problem because he wants an alert only and only when fragment A is showing not other and your code would create an alert on all fragments. – Pankaj Dec 05 '15 at 07:28
  • Yes in that case method 1 would be work well for shailesh and method 2 works for all fragments back button to be track but mothod 2 also preferable if we pass some conditions on it when backbutton is track – Kishan Soni Dec 05 '15 at 07:32
  • Method 1 wont work for him either i guess. because on clicking back button on any fragment would make the if condition true always for KEYCODE_BACK. – Pankaj Dec 05 '15 at 07:40
  • Nope it will work if he put method1 inside FragmentA because method1 we can put in any particular fragment and we can track that particular fragment's click. – Kishan Soni Dec 05 '15 at 08:54
  • You cant override `onKeyDown` method in `Fragment`. Do you know that? You can override in your `Activity` only, which is like `onBackPressed` method which you cant override in `Fragment` – Pankaj Dec 05 '15 at 14:26
  • @Clairvoyant i know it that's why i have mentioned in method 2 that if you want to use that code paste it on mainactivity so he also able to track entire app's backpressed – Kishan Soni Dec 08 '15 at 06:22
  • @KishanSoni thank sir.method 2 woking fine for me. – Gowthaman M Jun 15 '17 at 16:43
1

If you want to override the onBack pressed method then add this code in your in onActivityCreated() method

getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                      getFragmentManager().popBackStack();
                    return true;
                }
                return false;
            }
        });
Pavan Bilagi
  • 1,618
  • 1
  • 18
  • 23
0

Use the below code hope it helps.

//Always replace/add your fragment with a tag so that you can use that tag in future

     Fragment fr = getSupportFragmentManager().findFragmentByTag("Fragment_Name");//Fragment Name is a tag to identify fragment
     if (fr == null) {
     getSupportFragmentManager().beginTransaction()
     .replace(R.id.frame_container, new Demo_Fragment(), "Fragment_Name").commit();
     }

    //Now override onBackPressed method in MainActivity Only no need to do it in Fragment Class
    @Override
     public void onBackPressed() {
     Fragment fr = getSupportFragmentManager().findFragmentByTag("FragmentA");
    if(fr==null)
    //replace FragmentA
    else
    //Show Alert Box
     }
Surender Kumar
  • 1,123
  • 8
  • 15
0

For that you need to do following

Create method on the BaseFragment or Activity that save the current fragment object

 public void setCurrentFragment(Fragment currentFragment) {
                this.currentFragment = currentFragment;
               }

and also create a method that return your current fragment object

public Fragment getCurrentFragment() {
        return currentFragment;
    }

now just you need to call the getCurrentFragment Method and checked that if the Fragment is an instance of the A fragment or not

if (getCurrentFragment() instanceof AFragment) {
            showAlert
        } else {
            super.onBackPressed()
        }
Sandy
  • 985
  • 5
  • 13