Wednesday, 2 October 2013

OnBackPressed for fragments

Here is one of most common problems which is connected with onBackPressedFunction - how to implement onBackPressed() in Android Fragments?

And here is also my solution by using listeners to handle custom onBackPressed

According to @HaMMeRed answer here is pseudocode how should it works.
Lets say that your main activity is called BaseActivity (like in SlidingMenu example).
Here are the steps:

First we need create interface and class which implements its interface to have generic method

-1. Create class interface OnBackPressedListener

 public interface OnBackPressedListener {  
   public void doBack();  
 }  

0. Create class which implements skills of OnBackPressedListener

 public class BaseBackPressedListener implements OnBackPressedListener {  
   private final FragmentActivity activity;  
   public BaseBackPressedListener(FragmentActivity activity) {  
     this.activity = activity;  
   }  
   @Override  
   public void doBack() {  
     activity.getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);  
   }  
 }  

Since now, we will work on our code BaseActivity and its fragments..

1. Create private listener on top of your class
   
 protected OnBackPressedListener onBackPressedListener;  

2. Create method to set listener

 public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) {  
   this.onBackPressedListener = onBackPressedListener;  
 }  

3. In Override onBackPressed implement something like that

 @Override  
 public void onBackPressed() {  
   if (onBackPressedListener != null)  
     onBackPressedListener.doBack();  
   else  
     super.onBackPressed();  

4. in your fragment in onCreateView you should add our listener

 @Override  
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
   activity = getActivity();  
   ((BaseActivity)activity).setOnBackPressedListener(new BaseBackPressedListener(activity));  
   View view = ... ;  
 //stuff with view  
   return view;  
 }  

Now if you click back button listener should find custom class with custom onBackPressed reaction