Last active
May 17, 2020 09:41
-
-
Save manishkpr/e8132a80ba64806173d004bb36045b6f to your computer and use it in GitHub Desktop.
Android - handle back press in Fragment More Details Visit: http://manishkpr.webheavens.com
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This article describes how our FragmentBack works under the hood. | |
BaseFragment | |
First step to create back-sensitive fragments is to define interface that we can call to notify particular fragments about back-press. It contains only one method onBackPressed() which returns a value that indicates if back-press event was consumed by the fragment. | |
In this example we use base class, but you can define it via interface as well. | |
public class BaseFragment extends Fragment { | |
/** | |
* Could handle back press. | |
* @return true if back press was handled | |
*/ | |
public boolean onBackPressed() { | |
return false; | |
} | |
} | |
BaseActivity | |
The next step is an activity with overwritten Activity.onBackPressed() method. In its body we list all fragments attached to activity and for this implementing our BaseFragment class/interface we notify them about new back-press event. Notified fragment can indicate event consumption by returning true, in this case we stop iterating and leave the method. If no fragment consumeed the event we invoke standard Activity.onBackPressed() implementation to dismiss activity. | |
Now simply by extending this BaseActivity all back-press events will be propagated to all your BaseFragments placed in it. | |
public class BaseActivity extends Activity { | |
@Override | |
public void onBackPressed() { | |
List<Fragment> fragmentList = getSupportFragmentManager().getFragments(); | |
boolean handled = false; | |
for(Fragment f : fragmentList) { | |
if(f instanceof BaseFragment) { | |
handled = ((BaseFragment)f).onBackPressed(); | |
if(handled) { | |
break; | |
} | |
} | |
} | |
if(!handled) { | |
super.onBackPressed(); | |
} | |
} | |
} | |
MyFragment | |
Last step is to implement such back-sensitive fragment. There is nothing simpler, just extend/implement your BaseFragment class/interface and handle back-press events in onBackPressed() properly or just return false to ignore it. | |
public class MyFragment extends BaseFragment { | |
/** | |
* Back pressed send from activity. | |
* | |
* @return if event is consumed, it will return true. | |
*/ | |
@Override | |
public boolean onBackPressed() { | |
Toast.makeText(getActivity(), "Back Pressed", Toast.LENGTH_SHORT).show(); | |
return true; | |
} | |
} | |
We are done! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How about this implementaion with Dagger.
that s DaggerFragment and DaggerAppCompatActivity ..?