public interface OnBackPressedListener {
boolean onBackPressed();
}
public interface OnBackPressedNotifier {
void registerOnBackPressedListener(OnBackPressedListener listener);
void unregisterOnBackPressedListener(OnBackPressedListener listener);
}
public class SampleActivity extends Activity implements OnBackPressedNotifier {
List<OnBackPressedListener> onBackPressedListeners = new ArrayList<>();
@Override
public void registerOnBackPressedListener(OnBackPressedListener listener) {
if (!onBackPressedListeners.contains(listener))
onBackPressedListeners.add(listener);
}
@Override
public void unregisterOnBackPressedListener(OnBackPressedListener listener) {
if(onBackPressedListeners.contains(listener))
onBackPressedListeners.remove(listener);
}
@Override
protected void onDestroy() {
onBackPressedListeners.clear();
super.onDestroy();
}
private boolean notifyOnBackPressed(){
boolean handledByFragment = false;
for (OnBackPressedListener listener : onBackPressedListeners){
handledByFragment = listener.onBackPressed();
if (handledByFragment)
break;
}
return handledByFragment;
}
@Override
public void onBackPressed() {
if (!notifyOnBackPressed())
super.onBackPressed();
}
}
public class SampleFragment extends android.support.v4.app.Fragment implements OnBackPressedListener {
@Override
public void onAttach(Context context) {
super.onAttach(context);
((OnBackPressedNotifier)getActivity()).registerOnBackPressedListener(this);
}
@Override
public void onDetach() {
((OnBackPressedNotifier)getActivity()).unregisterOnBackPressedListener(this);
super.onDetach();
}
@Override
public boolean onBackPressed() {
// Handle onBackPressed
return false;
}