Java tutorial
/* * Copyright 2016 Alireza Eskandarpour Shoferi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.meness.easyintro.utils; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import io.github.meness.easyintro.listeners.OnBackPressListener; public class BackPressImpl implements OnBackPressListener { private final Fragment parentFragment; public BackPressImpl(Fragment parentFragment) { this.parentFragment = parentFragment; } @Override public boolean onBackPressed() { if (parentFragment == null) return false; int childCount = parentFragment.getChildFragmentManager().getBackStackEntryCount(); if (childCount == 0) { // it has no child Fragment // can not handle the onBackPressed task by itself return false; } else { // get the child Fragment FragmentManager childFragmentManager = parentFragment.getChildFragmentManager(); OnBackPressListener childFragment = (OnBackPressListener) childFragmentManager.getFragments().get(0); // propagate onBackPressed method call to the child Fragment if (!childFragment.onBackPressed()) { // child Fragment was unable to handle the task // It could happen when the child Fragment is last last leaf of a chain // removing the child Fragment from stack childFragmentManager.popBackStackImmediate(); } // either this Fragment or its child handled the task // either way we are successful and done here return true; } } }