Example usage for android.support.v4.app FragmentTransaction commitAllowingStateLoss

List of usage examples for android.support.v4.app FragmentTransaction commitAllowingStateLoss

Introduction

In this page you can find the example usage for android.support.v4.app FragmentTransaction commitAllowingStateLoss.

Prototype

public abstract int commitAllowingStateLoss();

Source Link

Document

Like #commit but allows the commit to be executed after an activity's state is saved.

Usage

From source file:com.ai.eve.lenovo.widget.FragmentTabHost.java

@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();
    String currentTab = getCurrentTabTag();
    FragmentTransaction ft = null;
    for (int i = 0; i < mTabs.size(); i++) {
        TabInfo tab = mTabs.get(i);//from   ww w  .ja  va 2s. c  o m
        tab.fragment = mFragmentManager.findFragmentByTag(tab.tag);
        if (tab.fragment != null && !tab.fragment.isDetached()) {
            if (tab.tag.equals(currentTab)) {
                mLastTab = tab;
            } else {
                if (ft == null) {
                    ft = mFragmentManager.beginTransaction();
                }
                ft.detach(tab.fragment);
            }
        }
    }
    mAttached = true;
    ft = doTabChanged(currentTab, ft);
    if (ft != null) {
        ft.commitAllowingStateLoss();
        mFragmentManager.executePendingTransactions();
    }
}

From source file:com.pindroid.activity.Main.java

private void replaceLeftFragment(Fragment frag, boolean backstack) {
    // Insert the fragment by replacing any existing fragment
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction t = fragmentManager.beginTransaction();
    t.replace(R.id.left_frame, frag, "left");
    if (backstack) {
        t.addToBackStack(null);//from  w  w  w.j a v  a  2s.  co  m
    }
    t.commitAllowingStateLoss();

    clearRightFragment();
}

From source file:com.openerp.MainActivity.java

public void startDetailFragment(Fragment fragment) {
    Log.d(TAG, "MainActivity->FragmentListener->startDetailFragment()");
    int container_id = (isTwoPane()) ? R.id.fragment_detail_container : R.id.fragment_container;
    FragmentTransaction tran = mFragment.beginTransaction().replace(container_id, fragment, "detail_fragment");
    if (!isTwoPane()) {
        tran.addToBackStack(null);//from   w  ww. j a  v  a2  s  .c  o m
        tran.commit();
    } else {
        findViewById(R.id.fragment_detail_container).setVisibility(View.VISIBLE);
        tran.commitAllowingStateLoss();
    }
}

From source file:cn.edu.zafu.corepage.core.CorePageManager.java

/**
 * ?/*from ww w .j a  v a2s . c om*/
 * fragemnt
 *
 * @param fragmentManager FragmentManager?
 * @param pageName  ???
 * @param bundle ?
 * @param animations 
 * @param addToBackStack ?
 * @return Fragment
 */
public Fragment openPageWithNewFragmentManager(FragmentManager fragmentManager, String pageName, Bundle bundle,
        int[] animations, boolean addToBackStack) {
    BaseFragment fragment = null;
    try {
        CorePage corePage = this.mPageMap.get(pageName);
        if (corePage == null) {
            Log.d(TAG, "Page:" + pageName + " is null");
            return null;
        }
        /**
         * Atlas? start
         */
        if (CoreConfig.isOpenAtlas()) {
            ClassLoader bundleClassLoader = CoreConfig.getBundleClassLoader();
            if (bundleClassLoader == null) {
                Log.d(TAG, "OpenAtlas bundle ClassLoader is null!");
                return null;
            }
            fragment = (BaseFragment) CoreConfig.getBundleClassLoader().loadClass(corePage.getClazz())
                    .newInstance();
        } else {
            fragment = (BaseFragment) Class.forName(corePage.getClazz()).newInstance();
        }
        /**
         * Atlas? end
         */

        Bundle pageBundle = buildBundle(corePage);
        if (bundle != null) {
            pageBundle.putAll(bundle);
        }
        fragment.setArguments(pageBundle);
        fragment.setPageName(pageName);

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (animations != null && animations.length >= 4) {
            fragmentTransaction.setCustomAnimations(animations[0], animations[1], animations[2], animations[3]);
        }
        Fragment fragmentContainer = fragmentManager.findFragmentById(R.id.fragment_container);
        if (fragmentContainer != null) {
            fragmentTransaction.hide(fragmentContainer);
        }

        fragmentTransaction.add(R.id.fragment_container, fragment, pageName);
        if (addToBackStack) {
            fragmentTransaction.addToBackStack(pageName);
        }

        fragmentTransaction.commitAllowingStateLoss();
        //fragmentTransaction.commit();

    } catch (Exception e) {
        e.printStackTrace();
        Log.d(TAG, "Fragment.error:" + e.getMessage());
        return null;
    }
    return fragment;
}

From source file:me.oriley.cratesample.activities.FragmentHelper.java

public final void showFragment(@NonNull BaseFragment fragment, @AnimationType int animationFlags,
        boolean addToBackStack, boolean replace) {
    if (!mActivity.isFinishing()) {
        String fragmentName = fragment.getClass().getSimpleName();
        FragmentTransaction ft = mFragmentManager.beginTransaction();

        int enterAnim = hasFlag(animationFlags, FLAG_ANIM_ENTER) ? mInAnimation : 0;
        int exitAnim = hasFlag(animationFlags, FLAG_ANIM_EXIT) ? mOutAnimation : 0;
        int enterPopAnim = hasFlag(animationFlags, FLAG_ANIM_POP_ENTER) ? mInPopAnimation : 0;
        int exitPopAnim = hasFlag(animationFlags, FLAG_ANIM_POP_EXIT) ? mOutPopAnimation : 0;

        ft.setCustomAnimations(enterAnim, exitAnim, enterPopAnim, exitPopAnim);
        if (addToBackStack) {
            ft.addToBackStack(fragmentName);
        }/*from   w  w  w .  j a  v  a  2 s .  c o m*/
        if (replace) {
            ft.replace(mFragmentContainerId, fragment, defaultTag(fragment.getClass()));
        } else {
            ft.add(mFragmentContainerId, fragment, defaultTag(fragment.getClass()));
        }
        ft.commitAllowingStateLoss();
    }
}

From source file:com.lastsoft.plog.GamesFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.fragment_games, container, false);

    rootView.setTag(TAG);//w  ww  . j a v  a  2  s .co m

    // BEGIN_INCLUDE(initializeRecyclerView)
    mCoordinatorLayout = (CoordinatorLayout) rootView.findViewById(R.id.coordinatorLayout);
    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
    mRecyclerView.setBackgroundColor(getResources().getColor(R.color.cardview_initial_background));
    pullToRefreshView = (SwipeRefreshLayout) rootView.findViewById(R.id.pull_to_refresh_listview);
    pullToRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            initDataset(true);
        }
    });

    RecyclerFastScroller fastScroller = (RecyclerFastScroller) rootView.findViewById(R.id.fastscroller);
    fastScroller.attachRecyclerView(mRecyclerView);
    //fastScroller = (VerticalRecyclerViewFastScroller) rootView.findViewById(R.id.fastscroller);

    // Connect the recycler to the scroller (to let the scroller scroll the list)
    //fastScroller.setRecyclerView(mRecyclerView, pullToRefreshView);

    // Connect the scroller to the recycler (to let the recycler scroll the scroller's handle)
    //mRecyclerView.setOnScrollListener(fastScroller.getOnScrollListener());

    addPlayer = (FloatingActionButton) rootView.findViewById(R.id.add_game);
    if (fromDrawer && playListType != 2) {
        //fastScroller.setRecyclerView(mRecyclerView, pullToRefreshView);
        mRecyclerView.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                boolean enable = false;
                boolean firstItemVisiblePull = recyclerView.getChildPosition(recyclerView.getChildAt(0)) == 0;
                boolean topOfFirstItemVisiblePull = recyclerView.getChildAt(0).getTop() == recyclerView
                        .getChildAt(0).getTop();
                ;
                enable = firstItemVisiblePull && topOfFirstItemVisiblePull;
                pullToRefreshView.setEnabled(enable);
            }
        });
        addPlayer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int viewXY[] = new int[2];
                v.getLocationOnScreen(viewXY);
                if (mListener != null) {
                    mListener.onFragmentInteraction("add_game", viewXY[0], viewXY[1]);
                }
            }
        });
    } else {
        if (!fromDrawer) {
            RelativeLayout gamesLayout = (RelativeLayout) rootView.findViewById(R.id.gamesLayout);
            final SwipeDismissBehavior<LinearLayout> behavior = new SwipeDismissBehavior();
            behavior.setSwipeDirection(SwipeDismissBehavior.SWIPE_DIRECTION_START_TO_END);
            behavior.setStartAlphaSwipeDistance(1.0f);
            behavior.setSensitivity(0.15f);
            behavior.setListener(new SwipeDismissBehavior.OnDismissListener() {
                @Override
                public void onDismiss(final View view) {
                    GamesFragment myFragC1 = (GamesFragment) getFragmentManager().findFragmentByTag("games");
                    FragmentTransaction transaction = getFragmentManager().beginTransaction();
                    transaction.remove(myFragC1);
                    transaction.commitAllowingStateLoss();
                    getFragmentManager().executePendingTransactions();
                    mActivity.onBackPressed();
                }

                @Override
                public void onDragStateChanged(int i) {

                }
            });

            CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) gamesLayout
                    .getLayoutParams();
            params.setBehavior(behavior);

        }
        //fastScroller.setRecyclerView(mRecyclerView, null);
        pullToRefreshView.setEnabled(false);
        addPlayer.setVisibility(View.GONE);
    }

    mProgress = (LinearLayout) rootView.findViewById(R.id.progressContainer);
    mText = (TextView) rootView.findViewById(R.id.LoadingText);

    // LinearLayoutManager is used here, this will layout the elements in a similar fashion
    // to the way ListView would layout elements. The RecyclerView.LayoutManager defines how
    // elements are laid out.
    mLayoutManager = new LinearLayoutManager(mActivity);

    mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;

    if (savedInstanceState != null) {
        // Restore saved layout manager type.
        mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState.getSerializable(KEY_LAYOUT_MANAGER);
    }
    setRecyclerViewLayoutManager(mCurrentLayoutManagerType);

    //mAdapter = new CustomAdapter(mDataset, mDataset_Thumb);
    mAdapter = new GameAdapter(this, mActivity, mSearchQuery, fromDrawer, playListType, sortType, fragmentName,
            currentYear);
    // Set CustomAdapter as the adapter for RecyclerView.
    mRecyclerView.setAdapter(mAdapter);

    if (mSearch != null) {
        mSearch.setHint(
                getString(R.string.filter) + mAdapter.getItemCount() + getString(R.string.filter_games));
    }

    fabMargin = getResources().getDimensionPixelSize(R.dimen.fab_margin);
    mRecyclerView.addOnScrollListener(new MyRecyclerScroll() {
        @Override
        public void show() {
            addPlayer.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
        }

        @Override
        public void hide() {
            addPlayer.animate().translationY(addPlayer.getHeight() + fabMargin)
                    .setInterpolator(new AccelerateInterpolator(2)).start();
        }
    });

    if (mSearch != null) {
        mSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                mSearchQuery = cs.toString();
                //initDataset();
                mAdapter = new GameAdapter(GamesFragment.this, mActivity, mSearchQuery, fromDrawer,
                        playListType, sortType, fragmentName, currentYear);
                // Set CustomAdapter as the adapter for RecyclerView.
                mRecyclerView.setAdapter(mAdapter);

                if (mSearch != null) {
                    mSearch.setHint(getString(R.string.filter) + mAdapter.getItemCount()
                            + getString(R.string.filter_games));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }

        });

        mCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!mSearch.getText().toString().equals("")) {
                    mSearchQuery = "";
                    mSearch.setText(mSearchQuery);
                    //mActivity.onBackPressed();
                }

                //fastScroller.scrollHider();

                InputMethodManager inputManager = (InputMethodManager) mActivity
                        .getSystemService(Context.INPUT_METHOD_SERVICE);

                inputManager.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
                mSearch.clearFocus();
                mRecyclerView.requestFocus();

                initDataset(false);

                if (mSearch != null) {
                    mSearch.setHint(getString(R.string.filter) + mAdapter.getItemCount()
                            + getString(R.string.filter_games));
                }
            }
        });
    }

    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    if (Game.findBaseGames("", sortType, year).size() == 0) {
        initDataset(false);
    } else {
        mText.setVisibility(View.GONE);
        mProgress.setVisibility(View.GONE);
        mRecyclerView.setVisibility(View.VISIBLE);
    }

    // END_INCLUDE(initializeRecyclerView)
    return rootView;
}

From source file:org.safegees.safegees.gui.view.PrincipalMapActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_IMAGE_CODE && resultCode == Activity.RESULT_OK) {
        //Set selected image as bitmap
        bitmap = ImageController.buildBitmapFromData(this, data.getData());
        //Send User Image
        this.sendUserImage();
    } else if (requestCode == REQUEST_CONTACTS_CODE && resultCode == Activity.RESULT_OK) {
        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out, R.anim.fade_in, R.anim.fade_out);
            transaction.remove(getActiveFragment());
            getSupportFragmentManager().popBackStack();
            transaction.commitAllowingStateLoss();
            this.floatingAddContactButton.hide();
        }/*w  w w. j a  va  2  s .  co m*/
        mapFragment.onResume();
        this.connectivityOn();
    } else if (requestCode == REQUEST_CONTACTS_CODE && resultCode == Activity.RESULT_CANCELED) {
        //Refresh the contacts fragment adapter list view
        if (this.contactsFragment != null) {
            this.contactsFragment.refresh();

        }
        //this.onBackPressed();
    }

    if (data != null) {
        //data != null when image data is received
        Log.e("DATA", data.getDataString());
        ProfileUserFragment myFragment = (ProfileUserFragment) getSupportFragmentManager()
                .findFragmentByTag("profile");
        if (myFragment != null && myFragment.isVisible()) {
            Log.i("ProfileFragment", "Add poto");
            myFragment.setImageBitmap(bitmap);
            //Store in /images
            ImageController.storeUserImage(this);
            //Reload the header image
            loadNavMenuProfile();
        }
    }

    //super.onActivityResult(requestCode, resultCode, data);
}

From source file:com.yanzhenjie.fragment.CompatActivity.java

/**
 * Show a fragment.//w w w .  j  a  v a2  s .  c om
 *
 * @param nowFragment    Now show fragment, can be null.
 * @param targetFragment fragment to display.
 * @param stickyStack    sticky back stack.
 * @param requestCode    requestCode.
 * @param <T>            {@link NoFragment}.
 */
public <T extends NoFragment> void startFragment(T nowFragment, T targetFragment, boolean stickyStack,
        int requestCode) {
    FragmentStackEntity fragmentStackEntity = new FragmentStackEntity();
    fragmentStackEntity.isSticky = stickyStack;
    fragmentStackEntity.requestCode = requestCode;
    targetFragment.setStackEntity(fragmentStackEntity);

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    if (nowFragment != null) {
        if (mFragmentEntityMap.get(nowFragment).isSticky) {
            nowFragment.onPause();
            nowFragment.onStop();
            fragmentTransaction.hide(nowFragment);
        } else {
            fragmentTransaction.remove(nowFragment);
            fragmentTransaction.commit();
            mFragmentStack.remove(nowFragment);
            mFragmentEntityMap.remove(nowFragment);

            fragmentTransaction = fragmentManager.beginTransaction();
        }
    }

    String fragmentTag = targetFragment.getClass().getSimpleName() + mAtomicInteger.incrementAndGet();
    fragmentTransaction.add(fragmentLayoutId(), targetFragment, fragmentTag);
    fragmentTransaction.addToBackStack(fragmentTag);
    fragmentTransaction.commitAllowingStateLoss();

    mFragmentStack.add(targetFragment);
    mFragmentEntityMap.put(targetFragment, fragmentStackEntity);
}

From source file:com.btmura.android.reddit.app.AbstractBrowserActivity.java

private <F extends Fragment & LeftFragment> void setLeftFragment(int containerId, ControlFragment controlFrag,
        F frag) {//  w w w.j av a 2  s.co m
    if (!Objects.equals(frag, getLeftFragment())) {
        safePopBackStackImmediate();

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(controlFrag, TAG_CONTROL_FRAGMENT);
        ft.replace(containerId, frag, TAG_LEFT_FRAGMENT);
        removeFragment(ft, TAG_RIGHT_FRAGMENT);
        ft.setTransition(
                FragmentTransaction.TRANSIT_FRAGMENT_OPEN | FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
        ft.commitAllowingStateLoss();

        refreshActionBar(null);
        refreshViews(null);
    }
}

From source file:com.bullmobi.base.ui.activities.SettingsActivity.java

/**
 * Switch to a specific Fragment with taking care of validation, Title and BackStack
 *//*w ww. j  a v  a 2  s .  c om*/
private Fragment switchToFragment(String fragmentName, Bundle args, boolean validate, boolean addToBackStack,
        int titleResId, CharSequence title, boolean withTransition) {
    if (validate && !isValidFragment(fragmentName)) {
        String message = "Invalid fragment for this activity: " + fragmentName;
        throw new IllegalArgumentException(message);
    }

    Fragment f = Fragment.instantiate(this, fragmentName, args);
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.main_content, f);

    if (withTransition && Device.hasKitKatApi())
        TransitionManager.beginDelayedTransition(mContent);
    if (addToBackStack)
        transaction.addToBackStack(SettingsActivity.BACK_STACK_PREFS);
    if (titleResId > 0) {
        transaction.setBreadCrumbTitle(titleResId);
    } else if (title != null) {
        transaction.setBreadCrumbTitle(title);
    }

    transaction.commitAllowingStateLoss();
    getFragmentManager().executePendingTransactions();
    return f;
}