Example usage for android.support.v4.app FragmentManager getBackStackEntryCount

List of usage examples for android.support.v4.app FragmentManager getBackStackEntryCount

Introduction

In this page you can find the example usage for android.support.v4.app FragmentManager getBackStackEntryCount.

Prototype

public abstract int getBackStackEntryCount();

Source Link

Document

Return the number of entries currently in the back stack.

Usage

From source file:com.nijie.samples.facebookfoo.FacebookFooMainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {

    Log.d("facebookfoo ###############", "FacebookFooMainActivity create!");
    super.onCreate(savedInstanceState);
    uiHelper = new UiLifecycleHelper(this, callback);
    uiHelper.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
        pendingAction = PendingAction.valueOf(name);
    }/*  w w w.  j a  v  a2s .  c o m*/

    setContentView(R.layout.main);

    loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton.setPublishPermissions(PAGE_PERMISSION);
    loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
        @Override
        public void onUserInfoFetched(GraphUser user) {
            FacebookFooMainActivity.this.user = user;
            Log.d("facebookfoo ###############", "onUserInfoFetched!");
            updateUI();
            // It's possible that we were waiting for this.user to be populated in order to post a
            // status update.
            handlePendingAction();
        }
    });

    profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
    greeting = (TextView) findViewById(R.id.greeting);

    postRegularPostButton = (Button) findViewById(R.id.regularPostUpdateButton);
    postRegularPostButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onClickPostRegularPost();
        }
    });

    postUnpublishedPostButton = (Button) findViewById(R.id.postUnpublishedPostButton);
    postUnpublishedPostButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onClickPostUnpublishedPost();
        }
    });

    listAllPostsButton = (Button) findViewById(R.id.listAllPostsButton);
    listAllPostsButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onClickListAllPosts();
        }
    });

    showStatisticsButton = (Button) findViewById(R.id.showStatisticsButton);
    showStatisticsButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onClickShowStatistics();
        }
    });

    controlsContainer = (ViewGroup) findViewById(R.id.main_ui_container);

    final FragmentManager fm = getSupportFragmentManager();
    Fragment fragment = fm.findFragmentById(R.id.fragment_container);
    if (fragment != null) {
        // If we're being re-created and have a fragment, we need to a) hide the main UI controls and
        // b) hook up its listeners again.
        controlsContainer.setVisibility(View.GONE);
        if (fragment instanceof FriendPickerFragment) {
            setFriendPickerListeners((FriendPickerFragment) fragment);
        } else if (fragment instanceof PlacePickerFragment) {
            setPlacePickerListeners((PlacePickerFragment) fragment);
        }
    }

    // Listen for changes in the back stack so we know if a fragment got popped off because the user
    // clicked the back button.
    fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            if (fm.getBackStackEntryCount() == 0) {
                // We need to re-show our UI.
                controlsContainer.setVisibility(View.VISIBLE);
            }
        }
    });

    // Can we present the share dialog for regular links?
    canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,
            FacebookDialog.ShareDialogFeature.SHARE_DIALOG);
    // Can we present the share dialog for photos?
    canPresentShareDialogWithPhotos = FacebookDialog.canPresentShareDialog(this,
            FacebookDialog.ShareDialogFeature.PHOTOS);

    Log.d("facebookfoo ###############", "OnCreate Exit!");
}

From source file:com.app.blockydemo.ui.ScriptActivity.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    FragmentManager fragmentManager = getSupportFragmentManager();

    for (String tag : FormulaEditorListFragment.TAGS) {
        FormulaEditorListFragment fragment = (FormulaEditorListFragment) fragmentManager.findFragmentByTag(tag);
        if (fragment != null) {
            if (fragment.isVisible()) {
                return fragment.onKey(null, keyCode, event);
            }//from w ww .  j a  va2  s.  co m
        }
    }

    FormulaEditorVariableListFragment formulaEditorVariableListFragment = (FormulaEditorVariableListFragment) getSupportFragmentManager()
            .findFragmentByTag(FormulaEditorVariableListFragment.VARIABLE_TAG);

    if (formulaEditorVariableListFragment != null) {
        if (formulaEditorVariableListFragment.isVisible()) {
            return formulaEditorVariableListFragment.onKey(null, keyCode, event);
        }
    }

    FormulaEditorFragment formulaEditor = (FormulaEditorFragment) getSupportFragmentManager()
            .findFragmentByTag(FormulaEditorFragment.FORMULA_EDITOR_FRAGMENT_TAG);

    if (formulaEditor != null) {
        if (formulaEditor.isVisible()) {
            scriptFragment.getAdapter().updateProjectBrickList();
            return formulaEditor.onKey(null, keyCode, event);
        }
    }

    int backStackEntryCount = fragmentManager.getBackStackEntryCount();
    for (int i = backStackEntryCount; i > 0; --i) {
        String backStackEntryName = fragmentManager.getBackStackEntryAt(i - 1).getName();
        if (backStackEntryName != null) {
            fragmentManager.popBackStack();
        } else {
            break;
        }
    }

    if (keyCode == KeyEvent.KEYCODE_BACK) {
        if (currentFragmentPosition == FRAGMENT_SCRIPTS) {
            DragAndDropListView listView = scriptFragment.getListView();
            if (listView.isCurrentlyDragging()) {
                listView.resetDraggingScreen();

                BrickAdapter adapter = scriptFragment.getAdapter();
                adapter.removeDraggedBrick();
                return true;
            }
        }
    }
    return super.onKeyDown(keyCode, event);
}

From source file:com.chatwing.whitelabel.activities.CommunicationActivity.java

@Override
public void onBackPressed() {
    if (mCurrentCommunicationMode.isSecondaryDrawerOpening()) {
        ((ChatboxModeManager) mCurrentCommunicationMode).closeSecondaryDrawer();
    } else if (!mCurrentCommunicationMode.isCommunicationBoxDrawerOpening()) {
        // Both online users and chat boxes/conversation lists are closed.
        // Open chat boxes/conversation list now.
        mCurrentCommunicationMode.openCommunicationBoxDrawer();
    } else {//from   w  w w  .j a v a2s.  com
        // Online users list is closed, chat boxes list is opened.
        // User probably is trying to quit the app.
        FragmentManager fragmentManager = getSupportFragmentManager();
        int stackSize = fragmentManager.getBackStackEntryCount();
        if (stackSize == 0) {
            finish();
        } else {
            String fragmentTag = fragmentManager.getBackStackEntryAt(stackSize - 1).getName();
            fragmentManager.popBackStack(fragmentTag, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
    }
}

From source file:at.fhooe.mcm.saap.facebook.HelloFacebookSampleActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    uiHelper = new UiLifecycleHelper(this, callback);
    uiHelper.onCreate(savedInstanceState);

    locationClient = new LocationClient(this, this, this);

    if (savedInstanceState != null) {
        String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
        pendingAction = PendingAction.valueOf(name);
    }//from  ww  w . j  a  va  2  s . c o  m

    setContentView(R.layout.main);

    loginButton = (LoginButton) findViewById(R.id.login_button);
    // loginButton.setFragment(this);
    loginButton.setReadPermissions(Arrays.asList("user_location", "user_birthday", "user_likes,",
            "user_interests", "user_activities", "user_friends", "user_actions.books"));
    loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
        @Override
        public void onUserInfoFetched(GraphUser user) {
            HelloFacebookSampleActivity.this.user = user;
            updateUI();
            // It's possible that we were waiting for this.user to
            // be populated in order to post a
            // status update.
            handlePendingAction();
        }
    });

    profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
    greeting = (TextView) findViewById(R.id.greeting);
    userTextView = (TextView) findViewById(R.id.userTextView);

    queryInterestsButton = (Button) findViewById(R.id.queryInterests);
    queryInterestsButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onClickQueryActivities();
        }
    });

    showActivitiesButton = (Button) findViewById(R.id.showActivities);
    showActivitiesButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onClickShowActivities();
        }
    });

    pickFriendsButton = (Button) findViewById(R.id.pickFriendsButton);
    pickFriendsButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onClickPickFriends();
        }
    });

    pickPlaceButton = (Button) findViewById(R.id.pickPlaceButton);
    pickPlaceButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onClickPickPlace();
        }
    });

    controlsContainer = (ViewGroup) findViewById(R.id.main_ui_container);

    final FragmentManager fm = getSupportFragmentManager();
    Fragment fragment = fm.findFragmentById(R.id.fragment_container);
    if (fragment != null) {
        // If we're being re-created and have a fragment, we need to a) hide
        // the main UI controls and
        // b) hook up its listeners again.
        controlsContainer.setVisibility(View.GONE);
        if (fragment instanceof FriendPickerFragment) {
            setFriendPickerListeners((FriendPickerFragment) fragment);
        } else if (fragment instanceof PlacePickerFragment) {
            setPlacePickerListeners((PlacePickerFragment) fragment);
        }
    }

    // Listen for changes in the back stack so we know if a fragment got
    // popped off because the user
    // clicked the back button.
    fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            if (fm.getBackStackEntryCount() == 0) {
                // We need to re-show our UI.
                controlsContainer.setVisibility(View.VISIBLE);
            }
        }
    });

    // Can we present the share dialog for regular links?
    canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,
            FacebookDialog.ShareDialogFeature.SHARE_DIALOG);
    // Can we present the share dialog for photos?
    canPresentShareDialogWithPhotos = FacebookDialog.canPresentShareDialog(this,
            FacebookDialog.ShareDialogFeature.PHOTOS);

    // init database if not initialized
    if (db == null) {
        //add activities
        db = new SQLiteHelper(getApplicationContext());
    }
}

From source file:com.gelakinetic.mtgfam.FamiliarActivity.java

/**
 * Select an item from the drawer menu. This will highlight the entry and manage fragment transactions.
 *
 * @param resId The string resource ID of the entry
 *///from  w  w  w .  ja  va 2s. c o m
private void selectItem(int resId, Bundle args, boolean shouldClearFragmentStack, boolean forceSelect) {

    int position = 0;
    for (DrawerEntry entry : mPageEntries) {
        if (resId == entry.mNameResource) {
            break;
        }
        position++;
    }

    mCurrentFrag = position;
    Fragment newFrag;
    /* Pick the new fragment */
    switch (resId) {
    case R.string.main_card_search: {
        /* If this is a quick search intent, launch either the card view or result list directly */
        if (args != null && args.containsKey(CardViewPagerFragment.CARD_ID_ARRAY)) {
            newFrag = new CardViewPagerFragment();
        } else if (args != null && args.containsKey(SearchViewFragment.CRITERIA)) {
            newFrag = new ResultListFragment();
        } else {
            newFrag = new SearchViewFragment();
        }
        break;
    }
    case R.string.main_life_counter: {
        newFrag = new LifeCounterFragment();
        break;
    }
    case R.string.main_mana_pool: {
        newFrag = new ManaPoolFragment();
        break;
    }
    case R.string.main_dice: {
        newFrag = new DiceFragment();
        break;
    }
    case R.string.main_trade: {
        newFrag = new TradeFragment();
        break;
    }
    case R.string.main_wishlist: {
        newFrag = new WishlistFragment();
        break;
    }
    case R.string.main_decklist: {
        newFrag = new DecklistFragment();
        break;
    }
    case R.string.main_timer: {
        newFrag = new RoundTimerFragment();
        break;
    }
    case R.string.main_rules: {
        newFrag = new RulesFragment();
        break;
    }
    case R.string.main_judges_corner: {
        newFrag = new JudgesCornerFragment();
        break;
    }
    case R.string.main_mojhosto: {
        newFrag = new MoJhoStoFragment();
        break;
    }
    case R.string.main_profile: {
        newFrag = new ProfileFragment();
        break;
    }
    default:
        return;
    }

    try {
        if (!forceSelect && ((Object) newFrag).getClass().equals(
                ((Object) getSupportFragmentManager().findFragmentById(R.id.fragment_container)).getClass())) {
            /* This is the same fragment, just close the menu */
            mDrawerLayout.closeDrawer(mDrawerList);
            return;
        }
    } catch (NullPointerException e) {
        /* no fragment to compare to */
    }

    if (args != null) {
        newFrag.setArguments(args);
    }

    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft;
    if (fm != null) {
        if (shouldClearFragmentStack) {
            /* Remove any current fragments on the back stack */
            while (fm.getBackStackEntryCount() > 0) {
                fm.popBackStackImmediate();
            }
        }

        /* Begin a new transaction */
        ft = fm.beginTransaction();

        /* Replace or add the fragment */
        ft.replace(R.id.fragment_container, newFrag, FamiliarActivity.FRAGMENT_TAG);
        if (!shouldClearFragmentStack) {
            ft.addToBackStack(null);
        }
        ft.commit();

        /* Color the icon when the fragment changes */
        View drawerListItemView = mDrawerList.getChildAt(position);
        if (drawerListItemView != null) {
            TextView textView = (TextView) drawerListItemView.findViewById(R.id.drawer_entry_name);
            if (textView != null) {
                mPagesAdapter.colorDrawerEntry(textView);
            }
        }
    }
}

From source file:org.gateshipone.odyssey.activities.OdysseyMainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.

    FragmentManager fragmentManager = getSupportFragmentManager();

    switch (item.getItemId()) {
    case android.R.id.home:
        if (fragmentManager.findFragmentById(R.id.fragment_container) instanceof FilesFragment) {
            // handle click events for the files fragment manually

            FilesFragment fragment = (FilesFragment) fragmentManager.findFragmentById(R.id.fragment_container);

            if (fragment.isRootDirectory()) {
                // current directory is a root directory so enable navigation drawer

                mDrawerToggle.setDrawerIndicatorEnabled(true);

                if (mDrawerToggle.onOptionsItemSelected(item)) {
                    return true;
                }/*from  w w  w  .jav a2 s  .c  o  m*/
            } else {
                // no root directory so create a new fragment with the parent directory
                List<String> storageVolumesList = mFileExplorerHelper
                        .getStorageVolumes(getApplicationContext());

                String parentDirectoryPath = fragment.getCurrentDirectory().getParent();

                onDirectorySelected(parentDirectoryPath, storageVolumesList.contains(parentDirectoryPath));
            }

        } else if (fragmentManager.getBackStackEntryCount() > 0) {
            onBackPressed();
        } else {
            // back stack empty so enable navigation drawer

            mDrawerToggle.setDrawerIndicatorEnabled(true);

            if (mDrawerToggle.onOptionsItemSelected(item)) {
                return true;
            }
        }
    }

    return super.onOptionsItemSelected(item);
}

From source file:org.catrobat.catroid.ui.ScriptActivity.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    FragmentManager fragmentManager = getSupportFragmentManager();

    for (String tag : FormulaEditorListFragment.TAGS) {
        FormulaEditorListFragment fragment = (FormulaEditorListFragment) fragmentManager.findFragmentByTag(tag);
        if (fragment != null && fragment.isVisible()) {
            return fragment.onKey(null, keyCode, event);
        }//w w w  .  j  a v  a 2s .  c  o m
    }

    String tag1 = UserBrickDataEditorFragment.BRICK_DATA_EDITOR_FRAGMENT_TAG;
    UserBrickDataEditorFragment fragment = (UserBrickDataEditorFragment) fragmentManager
            .findFragmentByTag(tag1);
    if (fragment != null && fragment.isVisible()) {
        return fragment.onKey(null, keyCode, event);
    }

    FormulaEditorDataFragment formulaEditorDataFragment = (FormulaEditorDataFragment) getSupportFragmentManager()
            .findFragmentByTag(FormulaEditorDataFragment.USER_DATA_TAG);

    if (formulaEditorDataFragment != null && formulaEditorDataFragment.isVisible()) {
        return formulaEditorDataFragment.onKey(null, keyCode, event);
    }

    FormulaEditorFragment formulaEditor = (FormulaEditorFragment) getSupportFragmentManager()
            .findFragmentByTag(FormulaEditorFragment.FORMULA_EDITOR_FRAGMENT_TAG);

    if (formulaEditor != null && formulaEditor.isVisible()) {
        scriptFragment.getAdapter().updateProjectBrickList();
        return formulaEditor.onKey(null, keyCode, event);
    }
    if (soundFragment != null && soundFragment.isVisible() && soundFragment.onKey(null, keyCode, event)) {
        return true;
    }

    if (lookFragment != null && lookFragment.isVisible() && lookFragment.onKey(null, keyCode, event)) {
        return true;
    }

    int backStackEntryCount = fragmentManager.getBackStackEntryCount();
    for (int i = backStackEntryCount; i > 0; --i) {
        String backStackEntryName = fragmentManager.getBackStackEntryAt(i - 1).getName();
        if (backStackEntryName != null && (backStackEntryName.equals(LookFragment.TAG)
                || backStackEntryName.equals(SoundFragment.TAG))) {
            fragmentManager.popBackStack();
        } else {
            break;
        }
    }

    if (keyCode == KeyEvent.KEYCODE_BACK && currentFragmentPosition == FRAGMENT_SCRIPTS) {
        DragAndDropListView listView = scriptFragment.getListView();
        if (listView.isCurrentlyDragging()) {
            listView.resetDraggingScreen();

            BrickAdapter adapter = scriptFragment.getAdapter();
            adapter.removeDraggedBrick();
            return true;
        }
    }

    return super.onKeyDown(keyCode, event);
}

From source file:com.example.android.threadsample.DisplayActivity.java

@Override
public void onCreate(Bundle stateBundle) {
    // Sets fullscreen-related flags for the display
    getWindow().setFlags(//  w w  w.jav a 2 s.  c  o m
            WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                    | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR,
            WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                    | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);

    // Calls the super method (required)
    super.onCreate(stateBundle);

    // Inflates the main View, which will be the host View for the fragments
    mMainView = getLayoutInflater().inflate(R.layout.fragmenthost, null);

    // Sets the content view for the Activity
    setContentView(mMainView);

    /*
     * Creates an intent filter for DownloadStateReceiver that intercepts broadcast Intents
     */

    // The filter's action is BROADCAST_ACTION
    IntentFilter statusIntentFilter = new IntentFilter(Constants.BROADCAST_ACTION);

    // Sets the filter's category to DEFAULT
    statusIntentFilter.addCategory(Intent.CATEGORY_DEFAULT);

    // Instantiates a new DownloadStateReceiver
    mDownloadStateReceiver = new DownloadStateReceiver();

    // Registers the DownloadStateReceiver and its intent filters
    LocalBroadcastManager.getInstance(this).registerReceiver(mDownloadStateReceiver, statusIntentFilter);

    /*
     * Creates intent filters for the FragmentDisplayer
     */

    // One filter is for the action ACTION_VIEW_IMAGE
    IntentFilter displayerIntentFilter = new IntentFilter(Constants.ACTION_VIEW_IMAGE);

    // Adds a data filter for the HTTP scheme
    displayerIntentFilter.addDataScheme("http");

    // Registers the receiver
    LocalBroadcastManager.getInstance(this).registerReceiver(mFragmentDisplayer, displayerIntentFilter);

    // Creates a second filter for ACTION_ZOOM_IMAGE
    displayerIntentFilter = new IntentFilter(Constants.ACTION_ZOOM_IMAGE);

    // Registers the receiver
    LocalBroadcastManager.getInstance(this).registerReceiver(mFragmentDisplayer, displayerIntentFilter);

    // Gets an instance of the support library FragmentManager
    FragmentManager localFragmentManager = getSupportFragmentManager();

    /*
     * Detects if side-by-side display should be enabled. It's only available on xlarge and
     * sw600dp devices (for example, tablets). The setting in res/values/ is "false", but this
     * is overridden in values-xlarge and values-sw600dp.
     */
    mSideBySide = getResources().getBoolean(R.bool.sideBySide);

    /*
     * Detects if hiding navigation controls should be enabled. On xlarge andsw600dp, it should
     * be false, to avoid having the user enter an additional tap.
     */
    mHideNavigation = getResources().getBoolean(R.bool.hideNavigation);

    /*
     * Adds the back stack change listener defined in this Activity as the listener for the
     * FragmentManager. See the method onBackStackChanged().
     */
    localFragmentManager.addOnBackStackChangedListener(this);

    // If the incoming state of the Activity is null, sets the initial view to be thumbnails
    if (null == stateBundle) {

        // Starts a Fragment transaction to track the stack
        FragmentTransaction localFragmentTransaction = localFragmentManager.beginTransaction();

        // Adds the PhotoThumbnailFragment to the host View
        localFragmentTransaction.add(R.id.fragmentHost, new PhotoThumbnailFragment(),
                Constants.THUMBNAIL_FRAGMENT_TAG);

        // Commits this transaction to display the Fragment
        localFragmentTransaction.commit();

        // The incoming state of the Activity isn't null.
    } else {

        // Gets the previous state of the fullscreen indicator
        mFullScreen = stateBundle.getBoolean(Constants.EXTENDED_FULLSCREEN);

        // Sets the fullscreen flag to its previous state
        setFullScreen(mFullScreen);

        // Gets the previous backstack entry count.
        mPreviousStackCount = localFragmentManager.getBackStackEntryCount();
    }
}

From source file:hku.fyp14017.blencode.ui.ScriptActivity.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    FragmentManager fragmentManager = getSupportFragmentManager();

    for (String tag : FormulaEditorListFragment.TAGS) {
        FormulaEditorListFragment fragment = (FormulaEditorListFragment) fragmentManager.findFragmentByTag(tag);
        if (fragment != null && fragment.isVisible()) {
            return fragment.onKey(null, keyCode, event);
        }/*  w  w w .j  a  v  a2 s  .com*/

    }

    String tag1 = UserBrickDataEditorFragment.BRICK_DATA_EDITOR_FRAGMENT_TAG;
    UserBrickDataEditorFragment fragment = (UserBrickDataEditorFragment) fragmentManager
            .findFragmentByTag(tag1);
    if (fragment != null && fragment.isVisible()) {
        return fragment.onKey(null, keyCode, event);
    }

    FormulaEditorVariableListFragment formulaEditorVariableListFragment = (FormulaEditorVariableListFragment) getSupportFragmentManager()
            .findFragmentByTag(FormulaEditorVariableListFragment.VARIABLE_TAG);

    if (formulaEditorVariableListFragment != null && formulaEditorVariableListFragment.isVisible()) {
        return formulaEditorVariableListFragment.onKey(null, keyCode, event);
    }

    SensorTagFragment sensorTagFragment = (SensorTagFragment) getSupportFragmentManager()
            .findFragmentByTag(SensorTagFragment.SENSOR_TAG_FRAGMENT_TAG);

    if (sensorTagFragment != null && sensorTagFragment.isVisible()) {
        return sensorTagFragment.onKey(null, keyCode, event);
    }

    FormulaEditorFragment formulaEditor = (FormulaEditorFragment) getSupportFragmentManager()
            .findFragmentByTag(FormulaEditorFragment.FORMULA_EDITOR_FRAGMENT_TAG);

    if (formulaEditor != null && formulaEditor.isVisible()) {
        scriptFragment.getAdapter().updateProjectBrickList();
        return formulaEditor.onKey(null, keyCode, event);
    }

    if (soundFragment != null && soundFragment.isVisible() && soundFragment.onKey(null, keyCode, event)) {
        return true;
    }

    if (lookFragment != null && lookFragment.isVisible() && lookFragment.onKey(null, keyCode, event)) {
        return true;
    }

    int backStackEntryCount = fragmentManager.getBackStackEntryCount();
    for (int i = backStackEntryCount; i > 0; --i) {
        String backStackEntryName = fragmentManager.getBackStackEntryAt(i - 1).getName();
        if (backStackEntryName != null && (backStackEntryName.equals(LookFragment.TAG)
                || backStackEntryName.equals(SoundFragment.TAG))) {
            fragmentManager.popBackStack();
        } else {
            break;
        }
    }

    if (keyCode == KeyEvent.KEYCODE_BACK && currentFragmentPosition == FRAGMENT_SCRIPTS) {
        DragAndDropListView listView = scriptFragment.getListView();
        if (listView.isCurrentlyDragging()) {
            listView.resetDraggingScreen();

            BrickAdapter adapter = scriptFragment.getAdapter();
            adapter.removeDraggedBrick();
            return true;
        }
    }

    return super.onKeyDown(keyCode, event);
}

From source file:org.gateshipone.odyssey.activities.OdysseyMainActivity.java

@Override
public void onBackPressed() {

    FragmentManager fragmentManager = getSupportFragmentManager();

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer != null && drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else if (mNowPlayingDragStatus == DRAG_STATUS.DRAGGED_UP) {
        NowPlayingView nowPlayingView = (NowPlayingView) findViewById(R.id.now_playing_layout);
        if (nowPlayingView != null) {
            View coordinatorLayout = findViewById(R.id.main_coordinator_layout);
            coordinatorLayout.setVisibility(View.VISIBLE);
            nowPlayingView.minimize();//from w w w.  ja  va2  s.c  o  m
        }
    } else if (fragmentManager.findFragmentById(R.id.fragment_container) instanceof SettingsFragment
            || fragmentManager.findFragmentById(R.id.fragment_container) instanceof SavedPlaylistsFragment) {
        // If current fragment is the settings or savedplaylists fragment, jump back to myMusicFragment.
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.fragment_container, new MyMusicFragment());
        transaction.commit();

        // Reset the navigation view
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        if (navigationView != null) {
            navigationView.setCheckedItem(R.id.nav_my_music);
        }
    } else if (fragmentManager.findFragmentById(R.id.fragment_container) instanceof FilesFragment) {
        // handle back pressed events for the files fragment manually

        FilesFragment fragment = (FilesFragment) fragmentManager.findFragmentById(R.id.fragment_container);

        if (fragment.isRootDirectory()) {
            // current directory is a root directory so handle back press normally
            super.onBackPressed();
        } else {
            // no root directory so create a new fragment with the parent directory
            List<String> storageVolumesList = mFileExplorerHelper.getStorageVolumes(getApplicationContext());

            String parentDirectoryPath = fragment.getCurrentDirectory().getParent();

            onDirectorySelected(parentDirectoryPath, storageVolumesList.contains(parentDirectoryPath));
        }
    } else {
        super.onBackPressed();

        // enable navigation bar when backstack empty
        if (fragmentManager.getBackStackEntryCount() == 0) {
            mDrawerToggle.setDrawerIndicatorEnabled(true);
        }
    }
}