Example usage for android.app FragmentTransaction addToBackStack

List of usage examples for android.app FragmentTransaction addToBackStack

Introduction

In this page you can find the example usage for android.app FragmentTransaction addToBackStack.

Prototype

public abstract FragmentTransaction addToBackStack(@Nullable String name);

Source Link

Document

Add this transaction to the back stack.

Usage

From source file:org.symptomcheck.capstone.ui.MainActivityOld.java

private void openFragment(Fragment fragment, boolean addToBackStack) {

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    if (addToBackStack) {
        fragmentTransaction.addToBackStack(null).replace(R.id.content_frame, fragment);
    } else {//  w ww.  ja va  2s .  com
        fragmentTransaction.replace(R.id.content_frame, fragment);
    }
    fragmentTransaction.commit();

}

From source file:org.akvo.caddisfly.ui.activity.MainActivity.java

void displayView(int position, boolean addToBackStack) {
    int index = getCurrentFragmentIndex();

    if (index == position) {
        // requested fragment is already showing
        return;/*w  w w.  j a  va  2s  .  co  m*/
    }

    MainApp mainApp = (MainApp) getApplicationContext();

    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Config.FLOW_ACTION_EXTERNAL_SOURCE.equals(action) && type != null) {
        if ("text/plain".equals(type)) { //NON-NLS
            external = true;
            //mQuestionId = getIntent().getStringExtra("questionId");
            mQuestionTitle = getIntent().getStringExtra("questionTitle");

            String code = mQuestionTitle.substring(Math.max(0, mQuestionTitle.length() - 5));

            mainApp.setSwatches(code);
        }
    }

    if (mainApp.currentTestInfo == null) {
        mainApp.currentTestInfo = new TestInfo("", "", "");
    }

    Fragment fragment;

    switch (position) {
    case Config.HOME_SCREEN_INDEX:
        mStartFragment = StartFragment.newInstance(external, mainApp.currentTestInfo.getCode());
        fragment = mStartFragment;
        break;
    case Config.CALIBRATE_SCREEN_INDEX:
        mCalibrateFragment = new CalibrateFragment();
        fragment = mCalibrateFragment;
        setupActionBarSpinner();

        break;
    case Config.SETTINGS_SCREEN_INDEX:
        if (mSettingsFragment == null) {
            mSettingsFragment = new SettingsFragment();
        }
        fragment = mSettingsFragment;
        break;
    default:
        return;
    }
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction ft = fragmentManager.beginTransaction();
    ft.replace(R.id.container, fragment, String.valueOf(position));
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    if (addToBackStack) {
        ft.addToBackStack(null);
    }
    ft.commit();

    invalidateOptionsMenu();
    updateActionBarNavigation(position);
}

From source file:fbla.hhs.eclat.Camera.Camera2BasicFragment.java

/**
 * Switch Fragments//from   w w  w.  j  a v  a2s.  co  m
 */
private void switchFrag() {
    ImagePreview fragment = new ImagePreview();
    fragment.setImage(mFile, this, cameraType);
    FragmentManager fragmentManager = getActivity().getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container, fragment);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

From source file:org.alfresco.mobile.android.application.fragments.browser.ChildrenBrowserFragment.java

public void createFolder() {
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    Fragment prev = getFragmentManager().findFragmentByTag(CreateFolderDialogFragment.TAG);
    if (prev != null) {
        ft.remove(prev);// w w w .  j  a  v a2s . co  m
    }
    ft.addToBackStack(null);

    // Create and show the dialog.
    AddFolderDialogFragment.newInstance(parentFolder).show(ft, CreateFolderDialogFragment.TAG);
}

From source file:org.chromium.chrome.browser.bookmark.ManageBookmarkActivity.java

/**
 * Creates and sets an action listener on the add/edit bookmark fragment.
 * @param addEditFragment The fragment that the listener should be attached to.
 *//* w ww.  j  av  a  2s  .co m*/
private void setActionListenerOnAddEdit(final AddEditBookmarkFragment addEditFragment) {
    addEditFragment.setOnActionListener(new AddEditBookmarkFragment.OnActionListener() {
        @Override
        public void onCancel() {
            finishAddEdit();
        }

        @Override
        public void onNodeEdited(long id) {
            finishAddEdit();
        }

        @Override
        public void onFolderCreated(long id, String name) {
            finishAddEdit();
            if (getFragmentManager().getBackStackEntryCount() != 0) {
                ((SelectBookmarkFolderFragment) addEditFragment.getTargetFragment()).executeFolderSelection(id,
                        name);
            }
        }

        @Override
        public void triggerFolderSelection() {
            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();

            boolean isRoot = getFragmentManager().getBackStackEntryCount() == 0;
            SelectBookmarkFolderFragment selectFolder = SelectBookmarkFolderFragment.newInstance(
                    // Only allow the root add/edit bookmark UI to create new bookmark
                    // folders during selection.
                    isRoot, addEditFragment.getParentFolderId(), addEditFragment.isFolder());
            selectFolder.setTargetFragment(addEditFragment, 0);
            setActionListenerOnFolderSelection(selectFolder);

            String tag = isRoot ? BASE_SELECT_FOLDER_FRAGMENT_TAG : ADD_FOLDER_SELECT_FOLDER_FRAGMENT_TAG;
            fragmentTransaction.add(android.R.id.content, selectFolder, tag);
            fragmentTransaction.hide(addEditFragment);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();
        }

        @Override
        public void onRemove() {
            finishAddEdit();
        }

        @Override
        public void setBackEnabled(boolean enabled) {
            mIsBackEnabled = enabled;
        }

        private void finishAddEdit() {
            if (getFragmentManager().getBackStackEntryCount() == 0) {
                finish();
            } else {
                getFragmentManager().popBackStackImmediate();
            }
        }
    });
}

From source file:org.akvo.caddisfly.sensor.colorimetry.liquid.ColorimetryLiquidActivity.java

private void startTest() {

    mResults = new ArrayList<>();

    mWaitingForStillness = false;//from ww  w  . j a va  2s  .c  o m
    mIsFirstResult = true;

    mShakeDetector.setMinShakeAcceleration(1);
    mShakeDetector.setMaxShakeDuration(MAX_SHAKE_DURATION_2);
    mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);

    (new AsyncTask<Void, Void, Void>() {

        @Nullable
        @Override
        protected Void doInBackground(Void... params) {
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            mCameraFragment = CameraDialogFragment.newInstance();

            mCameraFragment.setPictureTakenObserver(new CameraDialogFragment.PictureTaken() {
                @Override
                public void onPictureTaken(@NonNull byte[] bytes, boolean completed) {
                    Bitmap bitmap = ImageUtil.getBitmap(bytes);

                    Display display = getWindowManager().getDefaultDisplay();
                    int rotation;
                    switch (display.getRotation()) {
                    case Surface.ROTATION_0:
                        rotation = DEGREES_90;
                        break;
                    case Surface.ROTATION_180:
                        rotation = DEGREES_270;
                        break;
                    case Surface.ROTATION_270:
                        rotation = DEGREES_180;
                        break;
                    case Surface.ROTATION_90:
                    default:
                        rotation = 0;
                        break;
                    }

                    bitmap = ImageUtil.rotateImage(bitmap, rotation);

                    TestInfo testInfo = CaddisflyApp.getApp().getCurrentTestInfo();

                    Bitmap croppedBitmap;

                    if (testInfo.isUseGrayScale()) {
                        croppedBitmap = ImageUtil.getCroppedBitmap(bitmap,
                                ColorimetryLiquidConfig.SAMPLE_CROP_LENGTH_DEFAULT, false);

                        if (croppedBitmap != null) {
                            croppedBitmap = ImageUtil.getGrayscale(croppedBitmap);
                        }
                    } else {
                        croppedBitmap = ImageUtil.getCroppedBitmap(bitmap,
                                ColorimetryLiquidConfig.SAMPLE_CROP_LENGTH_DEFAULT, true);
                    }

                    //Ignore the first result as camera may not have focused correctly
                    if (!mIsFirstResult) {
                        if (croppedBitmap != null) {
                            getAnalyzedResult(croppedBitmap);
                        } else {
                            showError(
                                    String.format(TWO_SENTENCE_FORMAT, getString(R.string.chamberNotFound),
                                            getString(R.string.checkChamberPlacement)),
                                    ImageUtil.getBitmap(bytes));
                            mCameraFragment.stopCamera();
                            mCameraFragment.dismiss();
                            return;
                        }
                    }
                    mIsFirstResult = false;

                    if (completed) {
                        analyzeFinalResult(bytes, croppedBitmap);
                        mCameraFragment.dismiss();
                    } else {
                        sound.playShortResource(R.raw.beep);
                    }
                }
            });

            acquireWakeLock();

            delayRunnable = new Runnable() {
                @Override
                public void run() {
                    final FragmentTransaction ft = getFragmentManager().beginTransaction();
                    Fragment prev = getFragmentManager().findFragmentByTag("cameraDialog");
                    if (prev != null) {
                        ft.remove(prev);
                    }
                    ft.addToBackStack(null);
                    try {
                        mCameraFragment.show(ft, "cameraDialog");
                        mCameraFragment.takePictures(AppPreferences.getSamplingTimes(),
                                ColorimetryLiquidConfig.DELAY_BETWEEN_SAMPLING);
                    } catch (Exception e) {
                        Timber.e(e);
                        finish();
                    }
                }
            };

            delayHandler.postDelayed(delayRunnable, ColorimetryLiquidConfig.DELAY_BETWEEN_SAMPLING);

        }
    }).execute();
}

From source file:com.nuvolect.securesuite.main.ContactListActivity.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private ContactListFragment startContactListFragment() {

    boolean isDestroyed = false;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && m_act.isDestroyed())
        isDestroyed = true;/* w  ww  .ja  v a 2 s.c  o m*/

    if (m_act == null || isDestroyed || m_act.isFinishing())
        return null;

    ContactListFragment clf = new ContactListFragment();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.contact_list_container, clf, CConst.CONTACT_LIST_FRAGMENT_TAG);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    ft.addToBackStack(null);
    ft.commit();
    return clf;
}

From source file:iovi.testtask.MainActivity.java

private void selectItem(int position) {

    Fragment fragment = new ListF();
    FragmentManager fragmentManager;//from  w w  w . j av a 2s  .c  o  m
    FragmentTransaction fragmentTransaction;
    Bundle args = new Bundle();
    args.putString("Title", mMenuTitles[position]);

    switch (position) {
    case 0:
        args.putString(ListF.TABLE, DataBaseHelper.TABLE_ORGANISATIONS);
        args.putString(ListF.COLUMN, DataBaseHelper.NAME);
        args.putString(ListF.SELECTION, null);
        args.putStringArray(ListF.ARGS, null);
        fragment.setArguments(args);
        fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
        break;
    case 1:
        args.putString(ListF.TABLE, DataBaseHelper.TABLE_NEWS);
        args.putString(ListF.COLUMN, DataBaseHelper.NEWS_TITLE);
        args.putString(ListF.SELECTION, null);
        args.putStringArray(ListF.ARGS, null);
        fragment.setArguments(args);

        fragmentManager = getFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.content_frame, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
        break;

    case 2:
        fragment = new ContactsF();
        fragment.setArguments(args);
        fragmentManager = getFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.content_frame, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

        break;
    }

    // update selected item and title, then close the drawer
    mDrawerList.setItemChecked(position, true);
    setTitle(mMenuTitles[position]);
    mDrawerLayout.closeDrawer(mDrawerList);
}

From source file:com.door43.translationstudio.ui.dialogs.BackupDialog.java

/**
 * this is to fix old method which when called in onResume() would create a
 * second dialog overlaying the first.  The first was actually not removed.
 * Doing a commit after the remove() and starting a second FragmentTransaction
 * seems to fix the duplicate dialog bug.
 *
 * @param dialog/*from w  ww  .  java 2  s . com*/
 * @param tag
 */
private void showDialogFragment(android.app.DialogFragment dialog, String tag) {
    FragmentTransaction backupFt = getFragmentManager().beginTransaction();
    Fragment backupPrev = getFragmentManager().findFragmentByTag(tag);
    if (backupPrev != null) {
        backupFt.remove(backupPrev);
        backupFt.commit(); // apply the remove
        backupFt = getFragmentManager().beginTransaction(); // start a new transaction
    }
    backupFt.addToBackStack(null);

    dialog.show(backupFt, tag);
}

From source file:itcr.gitsnes.MainActivity.java

/**
 * OnCreate methods do that things://from   www .  java 2  s.c o m
 *      - Inflate Login formulary frame (hide action bar)
 *      - Init Accelerometer intent (onShake)
 *      - Create login method (auth with FB)
 *      - Handle exceptions of previously methods
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /* -- Shows action bar and inflate main Listview from JSON (see BackendHandler) --- */
    getActionBar().hide();
    setContentView(R.layout.activity_main);
    FragmentManager fm = getFragmentManager();
    FragmentTransaction transaction = fm.beginTransaction();

    /* Add transaction and login FB intent to mainActivity*/
    Login login = new Login();
    transaction.add(R.id.placeholder, login).commit();

    /* Init shake sensor and create event to get random game from DB (Backend on app-engine)*/
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mShakeDetector = new ShakeDetector();
    mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() {

        @Override
        public void onShake(int count) {
            /* Inflate random-game detail */
            Toast.makeText(getApplicationContext(), "Buscando juego aleatorio!!", Toast.LENGTH_SHORT).show();
            MasterGames new_fragment = new MasterGames(json_arr);
            new_fragment.setRandomgame("random");
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.replace(R.id.placeholder, new_fragment);
            transaction.addToBackStack(null);
            transaction.commit();

        }
    });

    mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);

    /*Initialize FB API helper methods and listen callback from fb_loginbutton*/

    uiHelper = new UiLifecycleHelper(this, callback);
    uiHelper.onCreate(savedInstanceState);
    authButton = (LoginButton) findViewById(R.id.authButton);
    authButton.setOnErrorListener(new LoginButton.OnErrorListener() {
        @Override
        public void onError(FacebookException error) {
            Log.i(TAG, "Error " + error.getMessage());
        }
    });

    /*Obtaining data from successfully FB API callback using GraphUser*/
    authButton.setReadPermissions(Arrays.asList("email"));
    authButton.setSessionStatusCallback(new Session.StatusCallback() {

        @Override
        public void call(Session session, SessionState state, Exception exception) {
            Log.i(TAG, "Accesssss Token");
            if (session.isOpened()) {
                Log.i(TAG, "Access Token" + session.getAccessToken());
                Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
                    @Override
                    public void onCompleted(GraphUser user, Response response) {
                        if (user != null) {
                            Log.i(TAG, "User ID " + user.getId());
                            Log.i(TAG, "Email " + user.asMap().get("email"));
                            /* Inflate main-Listview from JSON (see BackendHandler) and saving current user*/
                            back_stage();
                            getActionBar().show();
                            KS.setCurrent_user(user.asMap().get("email").toString());
                            Toast.makeText(getApplicationContext(), "Welcome!! " + KS.getCurrent_user(),
                                    Toast.LENGTH_SHORT).show();
                            new BackendHandler().sendUser(KS.getCurrent_user(),
                                    user.asMap().get("email").toString());
                            //lblEmail.setText(user.asMap().get("email").toString());
                        }
                    }
                });
            } else
                Log.i(TAG, "Nopes Token");
        }
    });
}