I want to implement onBackPressed in fragment which extends a DialogFragment
. But when overriding it gives an error that "method does not override its superclass".
How to implement it?
See here for a chunk of the code.

- 146
- 1
- 10
-
Please post specially the onBackPressed part of your source code. – gustavogbc Apr 20 '17 at 12:19
-
Please share your code and write details. – AGM Tazim Apr 20 '17 at 12:29
-
added code. Kindly review it and help me. – Swati Apr 20 '17 at 12:38
-
@Swati do you want to implement the backPressed functionality on Click of some specific view? and after click what kind of operation do want to perform? – pk4393 Apr 20 '17 at 12:46
-
I want that when i pressed back button then it went to previous activity in portrait mode. – Swati Apr 20 '17 at 12:50
-
Actually, I am trying to implement image rotation on device rotation. My first activity is in portrait mode then after click it went to full screen image view then that image rotate according to device rotation and when pressed back then it returns to previous activity in portrait mode. And i have to implement this in fragment which extends an dialog fragment . Review the chunk of code please. – Swati Apr 20 '17 at 12:53
-
Please post your code as text instead of as image. – gustavogbc Apr 20 '17 at 14:15
-
In order for us to help you we must see more from your code including annotations. But, with no more clues, my guess is that you are not implementing the `super.onBackPressed`. Please refer to http://stackoverflow.com/questions/5448653/how-to-implement-onbackpressed-in-fragments – gustavogbc Apr 20 '17 at 20:35
-
super.onBackPressed is not valid it does not take.Give me your mail id. @gustavogbc – Swati Apr 21 '17 at 05:02
6 Answers
Follow this. Its awesome example to implement onBackPressed()
functionality on Fragment
by using Abstract Class
.
1) Create an Abstract Class -
import android.app.Fragment;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
public abstract class BackableFragment extends Fragment implements View.OnKeyListener {
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener(this);
}
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackButtonPressed();
return true;
}
}
return false;
}
public abstract void onBackButtonPressed();
}
2) Implement the Abstract Class
to your Fragment
-
public class FragmentChannels extends BackableFragment {
...
@Override
public void onBackButtonPressed() {
if (doTheThingRequiringBackButtonOverride) {
// do the thing
} else {
getActivity().onBackPressed();
}
}
...
}
Thats it. Reference
Try this
private boolean exit = false;
/* your full actvivty */
@Override
public void onBackPressed() {
if (exit) {
super.onBackPressed();
return;
} else {
Toast.makeText(this, "Press Back again to Exit.", Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
exit = false;
}
}, 2000);
}
}

- 834
- 8
- 20
-
Thanks, but i don't want to implement press again to exit functionality. – Swati Apr 20 '17 at 12:39
-
actually you need to override backpress activity inside oncliklistner? – Nazim ch Apr 20 '17 at 12:45
-
I want that when i pressed back button then it went to previous activity in portrait mode. – Swati Apr 20 '17 at 12:54
When using fragments in your app, individual FragmentTransaction objects may represent context changes that should be added to the back stack. For example, if you are implementing a master/detail flow on a handset by swapping out fragments, you should ensure that pressing the Back button on a detail screen returns the user to the master screen. To do so, call addToBackStack() before you commit the transaction:
// Works with either the framework FragmentManager or the
// support package FragmentManager (getSupportFragmentManager).
getSupportFragmentManager().beginTransaction()
.add(detailFragment, "detail")
// Add this transaction to the back stack
.addToBackStack()
.commit();
If your application updates other user interface elements to reflect the current state of your fragments, such as the action bar, remember to update the UI when you commit the transaction. You should update your user interface after the back stack changes in addition to when you commit the transaction. You can listen for when a FragmentTransaction is reverted by setting up an FragmentManager.OnBackStackChangedListener:
getSupportFragmentManager().addOnBackStackChangedListener(
new FragmentManager.OnBackStackChangedListener() {
public void onBackStackChanged() {
// Update your UI here.
}
});

- 322
- 3
- 16
-
Thanks... but i don't want to apply a onClickListener on imageView. Simply, I want to rotate an image and when pressed back button then it return back to previous activity in portrait mode only. – Swati Apr 20 '17 at 13:13
@Swati as per your comment, you want to exit your current dialog as well as current activity. The dialog is another level of window that display on top of your current activity. The DialogFragment is just a shell which hold the actual dialog and manage the state such as device rotate.
The dialog itself has consume the keyevent include backpress as well. So there is no such backpress method on DialogFragment.
I would recommend you to get the dialog after it was created see here , override this method and let super class create the dialog then set dismiss listener to it. In the dismiss listener callback you can finish your activity and it will return to the previous activity. You can also use getDialog method which should work the same.

- 179
- 2
- 10
-
Thanks alot... Yes, you are right. Please provide me code for that. Thanks in advance. @vsatkh – Swati Apr 21 '17 at 06:33
-
@Swati, sorry I was at work so I can't reply you until now. Please visit my gist on github with the following link https://gist.github.com/cmidt-veasna/bab5dc37b8436d9d012f4fd394d02b84. My original approach suggested in the answer above won't work as somehow DialogFragment override the callback as it need to clean the state when dialog is disappear. – vsatkh Apr 21 '17 at 16:35
-
@Swati, also dismiss does not mean backpress event, It happen when dialog is dismissed. That's right, closing dialog cause dismiss callback to be executed. So be aware of that. – vsatkh Apr 21 '17 at 16:41
-
yes, you are right then how can i use backpress event on your code? image is not shown when dismiss event is applied. @vsatkh – Swati Apr 24 '17 at 06:38
Hi maybe I'm too late for the right anwser but this works for me
@Override
public void onResume() {
super.onResume();
if (getView() != null)
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener((v, keyCode, event) -> {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//TODO: Put here your action or method
return true;
}
}
return false;
});
}

- 121
- 5
You have code in you dialog fragment key listener method
dialog!!.setOnKeyListener { _ , keyCode, event ->
keyCode == KeyEvent.KEYCODE_BACK
}
By this even on back press click dialog fragment wont dismiss But you have to set dialog property as
dialog?.setCancelable(false)
dialog?.setCanceledOnTouchOutside(false)

- 84
- 7