Example usage for android.app FragmentManager beginTransaction

List of usage examples for android.app FragmentManager beginTransaction

Introduction

In this page you can find the example usage for android.app FragmentManager beginTransaction.

Prototype

public abstract FragmentTransaction beginTransaction();

Source Link

Document

Start a series of edit operations on the Fragments associated with this FragmentManager.

Usage

From source file:org.opendatakit.survey.activities.MainMenuActivity.java

public void swapToFragmentView(ScreenList newScreenType) {
    WebLogger.getLogger(getAppName()).i(t, "swapToFragmentView: " + newScreenType.name());
    FragmentManager mgr = getFragmentManager();
    FragmentTransaction trans = null;//w  ww.j  av  a2 s . c  om
    Fragment newFragment = null;
    if (newScreenType == ScreenList.MAIN_SCREEN) {
        throw new IllegalStateException("unexpected reference to generic main screen");
    } else if (newScreenType == ScreenList.FORM_CHOOSER) {
        newFragment = mgr.findFragmentByTag(newScreenType.name());
        if (newFragment == null) {
            newFragment = new FormChooserListFragment();
        }
    } else if (newScreenType == ScreenList.FRONT_PAGE) {
        newFragment = mgr.findFragmentByTag(newScreenType.name());
        if (newFragment == null) {
            newFragment = new FrontPageFragment();
        }
    } else if (newScreenType == ScreenList.INITIALIZATION_DIALOG) {
        newFragment = mgr.findFragmentByTag(newScreenType.name());
        if (newFragment == null) {
            newFragment = new InitializationFragment();
        }
    } else if (newScreenType == ScreenList.WEBKIT) {
        newFragment = mgr.findFragmentByTag(newScreenType.name());
        if (newFragment == null) {
            WebLogger.getLogger(getAppName()).i(t,
                    "[" + this.hashCode() + "] creating new webkit fragment " + newScreenType.name());
            newFragment = new WebViewFragment();
        }
    } else if (newScreenType == ScreenList.ABOUT_MENU) {
        newFragment = mgr.findFragmentByTag(newScreenType.name());
        if (newFragment == null) {
            newFragment = new AboutMenuFragment();
        }

    } else {
        throw new IllegalStateException("Unrecognized ScreenList type");
    }

    boolean matchingBackStackEntry = false;
    for (int i = 0; i < mgr.getBackStackEntryCount(); ++i) {
        BackStackEntry e = mgr.getBackStackEntryAt(i);
        WebLogger.getLogger(getAppName()).i(t, "BackStackEntry[" + i + "] " + e.getName());
        if (e.getName().equals(newScreenType.name())) {
            matchingBackStackEntry = true;
        }
    }

    if (matchingBackStackEntry) {
        if (trans != null) {
            WebLogger.getLogger(getAppName()).e(t, "Unexpected active transaction when popping state!");
            trans = null;
        }
        // flush backward, to the screen we want to go back to
        currentFragment = newScreenType;
        WebLogger.getLogger(getAppName()).e(t,
                "[" + this.hashCode() + "] popping back stack " + currentFragment.name());
        mgr.popBackStackImmediate(currentFragment.name(), 0);
    } else {
        // add transaction to show the screen we want
        if (trans == null) {
            trans = mgr.beginTransaction();
        }
        currentFragment = newScreenType;
        trans.replace(R.id.main_content, newFragment, currentFragment.name());
        WebLogger.getLogger(getAppName()).i(t,
                "[" + this.hashCode() + "] adding to back stack " + currentFragment.name());
        trans.addToBackStack(currentFragment.name());
    }

    // and see if we should re-initialize...
    if ((currentFragment != ScreenList.INITIALIZATION_DIALOG)
            && ((Survey) getApplication()).shouldRunInitializationTask(getAppName())) {
        WebLogger.getLogger(getAppName()).i(t, "swapToFragmentView -- calling clearRunInitializationTask");
        // and immediately clear the should-run flag...
        ((Survey) getApplication()).clearRunInitializationTask(getAppName());
        // OK we should swap to the InitializationFragment view
        // this will skip the transition to whatever screen we were trying to 
        // go to and will instead show the InitializationFragment view. We
        // restore to the desired screen via the setFragmentToShowNext()
        //
        // NOTE: this discards the uncommitted transaction.
        // Robolectric complains about a recursive state transition.
        if (trans != null) {
            trans.commit();
        }
        swapToFragmentView(ScreenList.INITIALIZATION_DIALOG);
    } else {
        // before we actually switch to a WebKit, be sure
        // we have the form definition for it...
        if (currentFragment == ScreenList.WEBKIT && getCurrentForm() == null) {
            // we were sent off to the initialization dialog to try to
            // discover the form. We need to inquire about the form again
            // and, if we cannot find it, report an error to the user.
            final Uri uriFormsProvider = FormsProviderAPI.CONTENT_URI;
            Uri uri = getIntent().getData();
            Uri formUri = null;

            if (uri.getScheme().equalsIgnoreCase(uriFormsProvider.getScheme())
                    && uri.getAuthority().equalsIgnoreCase(uriFormsProvider.getAuthority())) {
                List<String> segments = uri.getPathSegments();
                if (segments != null && segments.size() >= 2) {
                    String appName = segments.get(0);
                    setAppName(appName);
                    String tableId = segments.get(1);
                    String formId = (segments.size() > 2) ? segments.get(2) : null;
                    formUri = Uri.withAppendedPath(Uri.withAppendedPath(
                            Uri.withAppendedPath(FormsProviderAPI.CONTENT_URI, appName), tableId), formId);
                } else {
                    swapToFragmentView(ScreenList.FRONT_PAGE);
                    createErrorDialog(getString(R.string.invalid_uri_expecting_n_segments, uri.toString(), 2),
                            EXIT);
                    return;
                }
                // request specifies a specific formUri -- try to open that
                FormIdStruct newForm = FormIdStruct.retrieveFormIdStruct(getContentResolver(), formUri);
                if (newForm == null) {
                    // error
                    swapToFragmentView(ScreenList.FRONT_PAGE);
                    createErrorDialog(getString(R.string.form_not_found, segments.get(1)), EXIT);
                    return;
                } else {
                    transitionToFormHelper(uri, newForm);
                }
            }
        }

        if (trans != null) {
            trans.commit();
        }
        invalidateOptionsMenu();
    }
}

From source file:com.lgallardo.qbittorrentclient.RefreshListener.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Get preferences
    getSettings();/*  www  . ja v  a  2  s.co  m*/

    // Set alarm for checking completed torrents, if not set
    if (PendingIntent.getBroadcast(getApplication(), 0, new Intent(getApplication(), NotifierService.class),
            PendingIntent.FLAG_NO_CREATE) == null) {

        // Set Alarm for checking completed torrents
        alarmMgr = (AlarmManager) getApplication().getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(getApplication(), NotifierService.class);
        alarmIntent = PendingIntent.getBroadcast(getApplication(), 0, intent, 0);

        alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 5000,
                notification_period, alarmIntent);
    }

    // Set alarm for RSS checking, if not set
    if (PendingIntent.getBroadcast(getApplication(), 0, new Intent(getApplication(), RSSService.class),
            PendingIntent.FLAG_NO_CREATE) == null) {

        // Set Alarm for checking completed torrents
        alarmMgr = (AlarmManager) getApplication().getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(getApplication(), RSSService.class);
        alarmIntent = PendingIntent.getBroadcast(getApplication(), 0, intent, 0);

        alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 5000,
                AlarmManager.INTERVAL_DAY, alarmIntent);
    }

    // Set Theme (It must be fore inflating or setContentView)
    if (dark_ui) {
        this.setTheme(R.style.Theme_Dark);

        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().setNavigationBarColor(getResources().getColor(R.color.Theme_Dark_toolbarBackground));
            getWindow().setStatusBarColor(getResources().getColor(R.color.Theme_Dark_toolbarBackground));
        }
    } else {
        this.setTheme(R.style.Theme_Light);

        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().setNavigationBarColor(getResources().getColor(R.color.primary));
        }

    }

    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.app_bar);

    if (dark_ui) {
        toolbar.setBackgroundColor(getResources().getColor(R.color.Theme_Dark_primary));
    }

    setSupportActionBar(toolbar);

    // Set App title
    setTitle(R.string.app_shortname);

    // Drawer menu
    navigationDrawerServerItems = getResources().getStringArray(R.array.qBittorrentServers);
    navigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array);

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    //        drawerList = (ListView) findViewById(R.id.left_drawer);

    mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View
    mRecyclerView.setHasFixedSize(true); // Letting the system know that the list objects are

    ArrayList<DrawerItem> serverItems = new ArrayList<DrawerItem>();
    ArrayList<DrawerItem> actionItems = new ArrayList<DrawerItem>();
    //        ArrayList<ObjectDrawerItem> labelItems = new ArrayList<ObjectDrawerItem>();
    ArrayList<DrawerItem> settingsItems = new ArrayList<DrawerItem>();

    // Add server category
    serverItems.add(new DrawerItem(R.drawable.ic_drawer_servers,
            getResources().getString(R.string.drawer_servers_category), DRAWER_CATEGORY, false, null));

    // Server items
    int currentServerValue = 1;

    try {
        currentServerValue = Integer.parseInt(MainActivity.currentServer);
    } catch (NumberFormatException e) {

    }

    for (int i = 0; i < navigationDrawerServerItems.length; i++) {
        serverItems.add(new DrawerItem(R.drawable.ic_drawer_subitem, navigationDrawerServerItems[i],
                DRAWER_ITEM_SERVERS, ((i + 1) == currentServerValue), "changeCurrentServer"));

    }

    // Add actions
    actionItems.add(new DrawerItem(R.drawable.ic_drawer_all, navigationDrawerItemTitles[0], DRAWER_ITEM_ACTIONS,
            lastState.equals("all"), "refreshAll"));
    actionItems.add(new DrawerItem(R.drawable.ic_drawer_downloading, navigationDrawerItemTitles[1],
            DRAWER_ITEM_ACTIONS, lastState.equals("downloading"), "refreshDownloading"));
    actionItems.add(new DrawerItem(R.drawable.ic_drawer_completed, navigationDrawerItemTitles[2],
            DRAWER_ITEM_ACTIONS, lastState.equals("completed"), "refreshCompleted"));
    actionItems.add(new DrawerItem(R.drawable.ic_drawer_seeding, navigationDrawerItemTitles[3],
            DRAWER_ITEM_ACTIONS, lastState.equals("seeding"), "refreshSeeding"));
    actionItems.add(new DrawerItem(R.drawable.ic_drawer_paused, navigationDrawerItemTitles[4],
            DRAWER_ITEM_ACTIONS, lastState.equals("pause"), "refreshPaused"));
    actionItems.add(new DrawerItem(R.drawable.ic_drawer_active, navigationDrawerItemTitles[5],
            DRAWER_ITEM_ACTIONS, lastState.equals("active"), "refreshActive"));
    actionItems.add(new DrawerItem(R.drawable.ic_drawer_inactive, navigationDrawerItemTitles[6],
            DRAWER_ITEM_ACTIONS, lastState.equals("inactive"), "refreshInactive"));

    // Add labels

    // Add settings actions
    settingsItems.add(new DrawerItem(R.drawable.ic_action_options, navigationDrawerItemTitles[7],
            DRAWER_ITEM_ACTIONS, false, "openOptions"));
    settingsItems.add(new DrawerItem(R.drawable.ic_drawer_settings, navigationDrawerItemTitles[8],
            DRAWER_ITEM_ACTIONS, false, "openSettings"));

    if (packageName.equals("com.lgallardo.qbittorrentclient")) {
        settingsItems.add(new DrawerItem(R.drawable.ic_drawer_pro, navigationDrawerItemTitles[9],
                DRAWER_ITEM_ACTIONS, false, "getPro"));
        settingsItems.add(new DrawerItem(R.drawable.ic_drawer_help, navigationDrawerItemTitles[10],
                DRAWER_ITEM_ACTIONS, false, "openHelp"));
    } else {
        settingsItems.add(new DrawerItem(R.drawable.ic_drawer_help, navigationDrawerItemTitles[9],
                DRAWER_ITEM_ACTIONS, false, "openHelp"));
    }

    rAdapter = new DrawerItemRecyclerViewAdapter(getApplicationContext(), this, serverItems, actionItems,
            settingsItems, null);
    rAdapter.notifyDataSetChanged();

    //        drawerList.setAdapter(adapter);
    mRecyclerView.setAdapter(rAdapter);

    mLayoutManager = new LinearLayoutManager(this); // Creating a layout Manager
    mRecyclerView.setLayoutManager(mLayoutManager); // Setting the layout Manager

    // Set selection according to last state
    setSelectionAndTitle(lastState);

    // Get drawer title
    title = drawerTitle = getTitle();

    // Add the application icon control code inside MainActivity onCreate

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    // New ActionBarDrawerToggle for Google Material Desing (v7)
    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open,
            R.string.drawer_close) {

        /**
         * Called when a drawer has settled in a completely closed state.
         */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            // getSupportActionBar().setTitle(title);
        }

        /**
         * Called when a drawer has settled in a completely open state.
         */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            // getSupportActionBar().setTitle(drawerTitle);
            // setTitle(R.string.app_shortname);

        }
    };

    drawerLayout.setDrawerListener(drawerToggle);

    getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    getSupportActionBar().setHomeButtonEnabled(false);

    // Get options and save them as shared preferences
    qBittorrentOptions qso = new qBittorrentOptions();
    qso.execute(new String[] { qbQueryString + "/preferences", "getSettings" });

    // If it was awoken from an intent-filter,
    // get intent from the intent filter and Add URL torrent
    addTorrentByIntent(getIntent());

    // Fragments

    // Check whether the activity is using the layout version with
    // the fragment_container FrameLayout. If so, we must add the first
    // fragment
    if (findViewById(R.id.fragment_container) != null) {

        // However, if we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        // if (savedInstanceState != null) {
        // return;
        // }

        // This fragment will hold the list of torrents
        if (firstFragment == null) {
            firstFragment = new com.lgallardo.qbittorrentclient.ItemstFragment();
        }

        // This fragment will hold the list of torrents
        helpTabletFragment = new HelpFragment();

        // Set the second fragments container
        firstFragment.setSecondFragmentContainer(R.id.content_frame);

        // This i the second fragment, holding a default message at the
        // beginning
        secondFragment = new AboutFragment();

        // Add the fragment to the 'list_frame' FrameLayout
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        if (fragmentManager.findFragmentByTag("firstFragment") == null) {
            fragmentTransaction.add(R.id.list_frame, helpTabletFragment, "firstFragment");
        } else {
            fragmentTransaction.replace(R.id.list_frame, helpTabletFragment, "firstFragment");
        }

        if (fragmentManager.findFragmentByTag("secondFragment") == null) {
            fragmentTransaction.add(R.id.content_frame, secondFragment, "secondFragment");
        } else {
            fragmentTransaction.replace(R.id.content_frame, secondFragment, "secondFragment");
        }

        fragmentTransaction.commit();

        // Second fragment will be added in ItemsFragment's onListItemClick method

    } else {

        // Phones handle just one fragment

        // Create an instance of ItemsFragments
        if (firstFragment == null) {
            firstFragment = new com.lgallardo.qbittorrentclient.ItemstFragment();
        }
        firstFragment.setSecondFragmentContainer(R.id.one_frame);

        // This is the about fragment, holding a default message at the
        // beginning
        secondFragment = new AboutFragment();

        // If we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        //            if (savedInstanceState != null) {
        //
        //                // Handle Item list empty due to Fragment stack
        //                try {
        //                    FragmentManager fm = getFragmentManager();
        //
        //                    if (fm.getBackStackEntryCount() == 1 && fm.findFragmentById(R.id.one_frame) instanceof com.lgallardo.qbittorrentclient.TorrentDetailsFragment) {
        //
        //                        refreshCurrent();
        //
        //                    }
        //                }
        //                catch (Exception e) {
        //                }
        //
        //                return;
        //            }

        // Add the fragment to the 'list_frame' FrameLayout
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        if (fragmentManager.findFragmentByTag("firstFragment") == null) {
            fragmentTransaction.add(R.id.one_frame, secondFragment, "firstFragment");
        } else {
            fragmentTransaction.replace(R.id.one_frame, secondFragment, "firstFragment");
        }

        // if torrent details was loaded reset back button stack
        for (int i = 0; i < fragmentManager.getBackStackEntryCount(); ++i) {
            fragmentManager.popBackStack();
        }

        fragmentTransaction.commit();
    }

    // Activity is visible
    activityIsVisible = true;

    // First refresh
    refreshCurrent();

    handler = new Handler();
    handler.postDelayed(m_Runnable, refresh_period);

    // Load banner
    loadBanner();

}

From source file:com.android.calendar.AllInOneActivity.java

private void setMainPane(FragmentTransaction ft, int viewId, int viewType, long timeMillis, boolean force) {
    if (mOnSaveInstanceStateCalled) {
        return;//from w w w.  j av a2 s  .c  o m
    }
    if (!force && mCurrentView == viewType) {
        return;
    }

    // Remove this when transition to and from month view looks fine.
    boolean doTransition = viewType != ViewType.MONTH && mCurrentView != ViewType.MONTH;
    FragmentManager fragmentManager = getFragmentManager();
    // Check if our previous view was an Agenda view
    // TODO remove this if framework ever supports nested fragments
    if (mCurrentView == ViewType.AGENDA) {
        // If it was, we need to do some cleanup on it to prevent the
        // edit/delete buttons from coming back on a rotation.
        Fragment oldFrag = fragmentManager.findFragmentById(viewId);
        if (oldFrag instanceof AgendaFragment) {
            ((AgendaFragment) oldFrag).removeFragments(fragmentManager);
        }
    }

    if (viewType != mCurrentView) {
        // The rules for this previous view are different than the
        // controller's and are used for intercepting the back button.
        if (mCurrentView != ViewType.EDIT && mCurrentView > 0) {
            mPreviousView = mCurrentView;
        }
        mCurrentView = viewType;
    }
    // Create new fragment
    Fragment frag = null;
    Fragment secFrag = null;
    switch (viewType) {
    case ViewType.AGENDA:
        mNavigationView.getMenu().findItem(R.id.agenda_menu_item).setChecked(true);
        frag = new AgendaFragment(timeMillis, false);
        if (mIsTabletConfig) {
            mToolbar.setTitle(R.string.agenda_view);
        }
        break;
    case ViewType.DAY:
        mNavigationView.getMenu().findItem(R.id.day_menu_item).setChecked(true);
        frag = new DayFragment(timeMillis, 1);
        if (mIsTabletConfig) {
            mToolbar.setTitle(R.string.day_view);
        }
        break;
    case ViewType.MONTH:
        mNavigationView.getMenu().findItem(R.id.month_menu_item).setChecked(true);
        frag = new MonthByWeekFragment(timeMillis, false);
        if (mShowAgendaWithMonth) {
            secFrag = new AgendaFragment(timeMillis, false);
        }
        if (mIsTabletConfig) {
            mToolbar.setTitle(R.string.month_view);
        }
        break;
    case ViewType.WEEK:
    default:
        mNavigationView.getMenu().findItem(R.id.week_menu_item).setChecked(true);
        frag = new DayFragment(timeMillis, Utils.getDaysPerWeek(this));
        if (mIsTabletConfig) {
            mToolbar.setTitle(R.string.week_view);
        }
        break;
    }
    // Update the current view so that the menu can update its look according to the
    // current view.
    if (mCalendarToolbarHandler != null) {
        mCalendarToolbarHandler.setCurrentMainView(viewType);
    }

    if (!mIsTabletConfig) {
        refreshActionbarTitle(timeMillis);
    }

    // Show date only on tablet configurations in views different than Agenda
    if (!mIsTabletConfig) {
        mDateRange.setVisibility(View.GONE);
    } else if (viewType != ViewType.AGENDA) {
        mDateRange.setVisibility(View.VISIBLE);
    } else {
        mDateRange.setVisibility(View.GONE);
    }

    // Clear unnecessary buttons from the option menu when switching from the agenda view
    if (viewType != ViewType.AGENDA) {
        clearOptionsMenu();
    }

    boolean doCommit = false;
    if (ft == null) {
        doCommit = true;
        ft = fragmentManager.beginTransaction();
    }

    if (doTransition) {
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    }

    ft.replace(viewId, frag);
    if (mShowAgendaWithMonth) {

        // Show/hide secondary fragment

        if (secFrag != null) {
            ft.replace(R.id.secondary_pane, secFrag);
            mSecondaryPane.setVisibility(View.VISIBLE);
        } else {
            mSecondaryPane.setVisibility(View.GONE);
            Fragment f = fragmentManager.findFragmentById(R.id.secondary_pane);
            if (f != null) {
                ft.remove(f);
            }
            mController.deregisterEventHandler(R.id.secondary_pane);
        }
    }
    if (DEBUG) {
        Log.d(TAG, "Adding handler with viewId " + viewId + " and type " + viewType);
    }
    // If the key is already registered this will replace it
    mController.registerEventHandler(viewId, (EventHandler) frag);
    if (secFrag != null) {
        mController.registerEventHandler(viewId, (EventHandler) secFrag);
    }

    if (doCommit) {
        if (DEBUG) {
            Log.d(TAG, "setMainPane AllInOne=" + this + " finishing:" + this.isFinishing());
        }
        ft.commit();
    }
}

From source file:org.opendatakit.survey.android.activities.MainMenuActivity.java

public void swapToFragmentView(ScreenList newFragment) {
    WebLogger.getLogger(getAppName()).i(t, "swapToFragmentView: " + newFragment.toString());
    FragmentManager mgr = getFragmentManager();
    Fragment f;/*from w w w .ja v  a  2s.  com*/
    if (newFragment == ScreenList.MAIN_SCREEN) {
        throw new IllegalStateException("unexpected reference to generic main screen");
    } else if (newFragment == ScreenList.CUSTOM_VIEW) {
        WebLogger.getLogger(getAppName()).w(t,
                "swapToFragmentView: changing navigation to move to WebKit (was custom view)");
        f = mgr.findFragmentById(WebViewFragment.ID);
        if (f == null) {
            f = new WebViewFragment();
        }
        newFragment = ScreenList.WEBKIT;
    } else if (newFragment == ScreenList.FORM_CHOOSER) {
        f = mgr.findFragmentById(FormChooserListFragment.ID);
        if (f == null) {
            f = new FormChooserListFragment();
        }
    } else if (newFragment == ScreenList.INITIALIZATION_DIALOG) {
        if (currentFragment == ScreenList.INITIALIZATION_DIALOG) {
            WebLogger.getLogger(getAppName()).e(t, "Unexpected: currentFragment == INITIALIZATION_DIALOG");
            return;
        } else {
            f = mgr.findFragmentById(InitializationFragment.ID);
            if (f == null) {
                f = new InitializationFragment();
            }
            ((InitializationFragment) f).setFragmentToShowNext(
                    (currentFragment == null) ? ScreenList.FORM_CHOOSER.name() : currentFragment.name());
        }
    } else if (newFragment == ScreenList.FORM_DELETER) {
        f = mgr.findFragmentById(FormDeleteListFragment.ID);
        if (f == null) {
            f = new FormDeleteListFragment();
        }
    } else if (newFragment == ScreenList.FORM_DOWNLOADER) {
        f = mgr.findFragmentById(FormDownloadListFragment.ID);
        if (f == null) {
            f = new FormDownloadListFragment();
        }
    } else if (newFragment == ScreenList.INSTANCE_UPLOADER_TABLE_CHOOSER) {
        f = mgr.findFragmentById(InstanceUploaderTableChooserListFragment.ID);
        if (f == null) {
            f = new InstanceUploaderTableChooserListFragment();
        }
    } else if (newFragment == ScreenList.INSTANCE_UPLOADER) {
        f = mgr.findFragmentById(InstanceUploaderListFragment.ID);
        if (f == null) {
            f = new InstanceUploaderListFragment();
        }
        ((InstanceUploaderListFragment) f).changeUploadTableId();
    } else if (newFragment == ScreenList.WEBKIT) {
        f = mgr.findFragmentById(WebViewFragment.ID);
        if (f == null) {
            f = new WebViewFragment();
        }
    } else if (newFragment == ScreenList.ABOUT_MENU) {
        f = mgr.findFragmentById(AboutMenuFragment.ID);
        if (f == null) {
            f = new AboutMenuFragment();
        }

    } else {
        throw new IllegalStateException("Unrecognized ScreenList type");
    }

    FrameLayout shadow = (FrameLayout) findViewById(R.id.shadow_content);
    View frags = findViewById(R.id.main_content);
    View wkt = findViewById(R.id.webkit_view);
    shadow.setVisibility(View.GONE);
    shadow.removeAllViews();
    if (newFragment == ScreenList.WEBKIT) {
        frags.setVisibility(View.GONE);
        wkt.setVisibility(View.VISIBLE);
        wkt.invalidate();
    } else {
        wkt.setVisibility(View.GONE);
        frags.setVisibility(View.VISIBLE);
    }

    currentFragment = newFragment;
    BackStackEntry entry = null;
    for (int i = 0; i < mgr.getBackStackEntryCount(); ++i) {
        BackStackEntry e = mgr.getBackStackEntryAt(i);
        if (e.getName().equals(currentFragment.name())) {
            entry = e;
            break;
        }
    }
    if (entry != null) {
        // flush backward, including the screen want to go back to
        mgr.popBackStackImmediate(currentFragment.name(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

    // add transaction to show the screen we want
    FragmentTransaction trans = mgr.beginTransaction();
    trans.replace(R.id.main_content, f);
    trans.addToBackStack(currentFragment.name());
    trans.commit();

    // and see if we should re-initialize...
    if ((currentFragment != ScreenList.INITIALIZATION_DIALOG)
            && Survey.getInstance().shouldRunInitializationTask(getAppName())) {
        WebLogger.getLogger(getAppName()).i(t, "swapToFragmentView -- calling clearRunInitializationTask");
        // and immediately clear the should-run flag...
        Survey.getInstance().clearRunInitializationTask(getAppName());
        // OK we should swap to the InitializationFragment view
        swapToFragmentView(ScreenList.INITIALIZATION_DIALOG);
    } else {
        levelSafeInvalidateOptionsMenu();
    }
}

From source file:com.bernard.beaconportal.activities.activity.MessageList.java

private void initializeFragments() {
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.addOnBackStackChangedListener(this);

    boolean hasMessageListFragment = (mMessageListFragment != null);

    if (!hasMessageListFragment) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        mMessageListFragment = MessageListFragment.newInstance(mSearch, false,
                (K9.isThreadedViewEnabled() && !mNoThreading));
        ft.add(R.id.message_list_container, mMessageListFragment);
        ft.commit();/*  www.j  av  a2s  . c o m*/
    }

    // Check if the fragment wasn't restarted and has a MessageReference in
    // the arguments. If
    // so, open the referenced message.
    if (!hasMessageListFragment && mMessageViewFragment == null && mMessageReference != null) {
        openMessage(mMessageReference);
    }
}

From source file:com.bernard.beaconportal.activities.activity.MessageList.java

/**
 * Create fragment instances if necessary.
 * /*from   w w  w .  java2s .c  o m*/
 * @see #findFragments()
 */

private void removeFragments() {
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.addOnBackStackChangedListener(this);

    boolean hasMessageListFragment = (mMessageListFragment != null);

    if (!hasMessageListFragment) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        mMessageListFragment = MessageListFragment.newInstance(mSearch, false,
                (K9.isThreadedViewEnabled() && !mNoThreading));
        // ft.remove(mMessageListFragment);
        ft.commit();

        Log.d("removed fragment?", "yes");
    }

    // Check if the fragment wasn't restarted and has a MessageReference in
    // the arguments. If
    // so, open the referenced message.
    if (!hasMessageListFragment && mMessageViewFragment == null && mMessageReference != null) {
        openMessage(mMessageReference);
    }
}

From source file:de.anderdonau.spacetrader.Main.java

public void changeFragment(FRAGMENTS fragment) {
    hide_keyboard(this);
    if (fragment == gameState.currentState && currentFragment != null) {
        // Sometimes this seems to be unset. Try to workaround it.
        currentFragment.gameState = gameState;
        if (currentFragment.update()) {
            return;
        }/*from  w  ww  . j ava  2 s  . c o m*/
    }
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();

    if (fragment == FRAGMENTS.NEW_GAME || fragment == FRAGMENTS.ENCOUNTER) {
        transaction.hide(mNavigationDrawerFragment);
    } else {
        transaction.show(mNavigationDrawerFragment);
    }

    Bundle args = new Bundle();
    args.putSerializable("gamestate", gameState);

    switch (fragment) {
    case AVERAGE_PRICES:
        currentFragment = new FragmentAveragePrices();
        break;
    case BANK:
        currentFragment = new FragmentBank();
        break;
    case BUY_CARGO:
        currentFragment = new FragmentBuyCargo();
        break;
    case BUY_EQUIPMENT:
        currentFragment = new FragmentBuyEquipment();
        break;
    case BUY_NEW_SHIP:
        currentFragment = new FragmentBuyNewShip();
        break;
    case COMMANDER_STATUS:
        currentFragment = new FragmentCommanderStatus();
        break;
    case DUMP:
        currentFragment = new FragmentDumpCargo();
        break;
    case ENCOUNTER:
        currentFragment = new FragmentEncounter();
        break;
    case GALACTIC_CHART:
        currentFragment = new FragmentGalacticChart();
        break;
    case NEW_GAME:
        currentFragment = new FragmentStartNewGame();
        break;
    case OPTIONS:
        currentFragment = new FragmentOptions();
        break;
    case PERSONNEL_ROSTER:
        currentFragment = new FragmentPersonnelRoster();
        break;
    case PLUNDER:
        currentFragment = new FragmentPlunderCargo();
        break;
    case SELL_CARGO:
        currentFragment = new FragmentSellCargo();
        break;
    case SELL_EQUIPMENT:
        currentFragment = new FragmentSellEquipment();
        break;
    case SHIPYARD:
        currentFragment = new FragmentShipyard();
        break;
    case SHIP_INFO:
        currentFragment = new FragmentShipInfo();
        break;
    case SHORTCUTS:
        currentFragment = new FragmentShortcuts();
        break;
    case SHORT_RANGE_CHART:
        currentFragment = new FragmentShortRangeChart();
        break;
    case SYSTEM_INFORMATION:
        currentFragment = new FragmentSystemInformation();
        break;
    case VERY_RARE_CHEAT:
        currentFragment = new FragmentVeryRare();
        break;
    case WARP_SYSTEM_INFORMATION:
        currentFragment = new FragmentWarpSystemInformation();
        break;
    default:
        return;
    }

    currentFragment.setArguments(args);
    transaction.replace(R.id.container, currentFragment);
    transaction.commit();
    gameState.currentState = fragment;

    invalidateOptionsMenu();
}

From source file:de.anderdonau.spacetrader.Main.java

@SuppressWarnings("ConstantConditions")
@Override/*from   w w  w.  j  a  v  a 2  s . c om*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = getApplicationContext();

    SharedPreferences sp = getSharedPreferences("spacetrader", MODE_PRIVATE);
    String theme = sp.getString("Theme", "Light");
    if ("Light".equals(theme)) {
        setTheme(R.style.AppTheme_Light);
    } else {
        setTheme(R.style.AppTheme);
    }

    setContentView(R.layout.activity_welcome_screen);
    FragmentManager fragmentManager = getFragmentManager();

    // Set up the drawer.
    DrawerLayout drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mNavigationDrawerFragment = (NavigationDrawerFragment) fragmentManager
            .findFragmentById(R.id.navigation_drawer);
    mNavigationDrawerFragment.setUp(R.id.navigation_drawer, drawer_layout);
    fragmentManager.beginTransaction().hide(mNavigationDrawerFragment).commit();

    populateBitmaps();
    boolean gameLoaded = false;

    try {
        File path = new File(Environment.getExternalStorageDirectory().toString() + "/SpaceTrader");
        File f = new File(path, "savegame.txt");
        FileInputStream fis = new FileInputStream(f);
        ObjectInputStream ois = new ObjectInputStream(fis);
        SaveGame_v110 s = (SaveGame_v110) ois.readObject();
        gameState = new GameState(s);
        GameState.isValid = true;
        gameLoaded = true;
        ois.close();
        fis.close();
        changeFragment(FRAGMENTS.SYSTEM_INFORMATION);
    } catch (Exception ignored) {
    }

    if (!gameLoaded) {
        try {
            File path = new File(Environment.getExternalStorageDirectory().toString() + "/SpaceTrader");
            File f = new File(path, "savegame.txt");
            FileInputStream fis = new FileInputStream(f);
            ObjectInputStream ois = new ObjectInputStream(fis);
            SaveGame_v111 s = (SaveGame_v111) ois.readObject();
            gameState = new GameState(s);
            GameState.isValid = true;
            gameLoaded = true;
            ois.close();
            fis.close();
            changeFragment(FRAGMENTS.SYSTEM_INFORMATION);
        } catch (Exception ignored) {
        }
    }

    if (!gameLoaded) {
        try {
            File path = new File(Environment.getExternalStorageDirectory().toString() + "/SpaceTrader");
            File f = new File(path, "savegame.txt");
            FileInputStream fis = new FileInputStream(f);
            ObjectInputStream ois = new ObjectInputStream(fis);
            SaveGame_v120 s = (SaveGame_v120) ois.readObject();
            gameState = new GameState(s);
            WarpSystem = gameState.SolarSystem[gameState.WarpSystem];
            GameState.isValid = true;
            gameLoaded = true;
            ois.close();
            fis.close();
            changeFragment(gameState.currentState);
        } catch (Exception ignored) {
        }
    }

    if (!gameLoaded) {
        gameState = new GameState(this, "Jameson");
        changeFragment(FRAGMENTS.NEW_GAME);
    }
}

From source file:org.path.episample.android.activities.MainMenuActivity.java

public void swapToFragmentView(ScreenList newFragment) {
    WebLogger.getLogger(getAppName()).i(t, "swapToFragmentView: " + newFragment.toString());

    String get = PropertiesSingleton.getProperty("survey",
            AdminPreferencesActivity.KEY_TURN_ON_OFF_WIFI_AUTOMATICALLY);
    if (!(get != null && get.equalsIgnoreCase("false"))) {
        if (mWifiManager.isWifiEnabled() && mWifiManager.getWifiState() != WifiManager.WIFI_STATE_DISABLED) {
            mWifiManager.setWifiEnabled(false);
        }/*from  ww w . ja  v  a 2s .  co m*/
    }

    FragmentManager mgr = getFragmentManager();
    Fragment f;
    if (newFragment == ScreenList.MAIN_SCREEN) {
        throw new IllegalStateException("unexpected reference to generic main screen");
    } else if (newFragment == ScreenList.CUSTOM_VIEW) {
        WebLogger.getLogger(getAppName()).w(t,
                "swapToFragmentView: changing navigation to move to WebKit (was custom view)");
        f = mgr.findFragmentById(WebViewFragment.ID);
        if (f == null) {
            f = new WebViewFragment();
        }
        newFragment = ScreenList.WEBKIT;
    } else if (newFragment == ScreenList.MAIN_MENU) {
        f = mgr.findFragmentById(MainMenuFragment.ID);
        if (f == null) {
            f = new MainMenuFragment();
        }
    } else if (newFragment == ScreenList.COLLECT_MODULE) {
        f = mgr.findFragmentById(CollectFragment.ID);
        if (f == null) {
            f = new CollectFragment();
        }
    } else if (newFragment == ScreenList.SEND_RECEIVE_WIFI_DIRECT_MODULE) {
        f = mgr.findFragmentById(SendReceiveFragment.ID);
        if (f == null) {
            f = new SendReceiveFragment();
        }
    } /*else if (newFragment == ScreenList.SEND_RECEIVE_BLUETOOTH_MODULE) {
       f = mgr.findFragmentById(SendReceiveFragmentBT.ID);
       if (f == null) {
          f = new SendReceiveFragmentBT();
       }
      }*/ else if (newFragment == ScreenList.SELECT_MODULE) {
        f = mgr.findFragmentById(SelectFragment.ID);
        if (f == null) {
            f = new SelectFragment();
        }
    } else if (newFragment == ScreenList.NAVIGATE_MODULE) {
        f = mgr.findFragmentById(NavigateFragment.ID);
        if (f == null) {
            f = new NavigateFragment();
        }
    } else if (newFragment == ScreenList.RESTORE_MODULE) {
        f = mgr.findFragmentById(RestoreFragment.ID);
        if (f == null) {
            f = new RestoreFragment();
        }
    } else if (newFragment == ScreenList.EDIT_CENSUS_MODULE) {
        f = mgr.findFragmentById(EditCensusFragment.ID);
        if (f == null) {
            f = new EditCensusFragment();
        }
    } else if (newFragment == ScreenList.REMOVE_CENSUS_MODULE) {
        f = mgr.findFragmentById(RemoveCensusFragment.ID);
        if (f == null) {
            f = new RemoveCensusFragment();
        }
    } else if (newFragment == ScreenList.INVALIDATE_CENSUS_MODULE) {
        f = mgr.findFragmentById(InvalidateCensusFragment.ID);
        if (f == null) {
            f = new InvalidateCensusFragment();
        }
    } else if (newFragment == ScreenList.FORM_CHOOSER) {
        f = mgr.findFragmentById(FormChooserListFragment.ID);
        if (f == null) {
            f = new FormChooserListFragment();
        }
    } else if (newFragment == ScreenList.INITIALIZATION_DIALOG) {
        if (currentFragment == ScreenList.INITIALIZATION_DIALOG) {
            WebLogger.getLogger(getAppName()).e(t, "Unexpected: currentFragment == INITIALIZATION_DIALOG");
            return;
        } else {
            f = mgr.findFragmentById(InitializationFragment.ID);
            if (f == null) {
                f = new InitializationFragment();
            }
            ((InitializationFragment) f).setFragmentToShowNext(
                    (currentFragment == null) ? ScreenList.FORM_CHOOSER.name() : currentFragment.name());
        }
    } else if (newFragment == ScreenList.FORM_DELETER) {
        f = mgr.findFragmentById(FormDeleteListFragment.ID);
        if (f == null) {
            f = new FormDeleteListFragment();
        }
    } else if (newFragment == ScreenList.FORM_DOWNLOADER) {
        f = mgr.findFragmentById(FormDownloadListFragment.ID);
        if (f == null) {
            f = new FormDownloadListFragment();
        }
    } else if (newFragment == ScreenList.INSTANCE_UPLOADER_TABLE_CHOOSER) {
        f = mgr.findFragmentById(InstanceUploaderTableChooserListFragment.ID);
        if (f == null) {
            f = new InstanceUploaderTableChooserListFragment();
        }
    } else if (newFragment == ScreenList.INSTANCE_UPLOADER) {
        f = mgr.findFragmentById(InstanceUploaderListFragment.ID);
        if (f == null) {
            f = new InstanceUploaderListFragment();
        }
        ((InstanceUploaderListFragment) f).changeUploadTableId();
    } else if (newFragment == ScreenList.WEBKIT) {
        f = mgr.findFragmentById(WebViewFragment.ID);
        if (f == null) {
            f = new WebViewFragment();
        }
    } else if (newFragment == ScreenList.ABOUT_MENU) {
        f = mgr.findFragmentById(AboutMenuFragment.ID);
        if (f == null) {
            f = new AboutMenuFragment();
        }

    } else {
        throw new IllegalStateException("Unrecognized ScreenList type");
    }

    FrameLayout shadow = (FrameLayout) findViewById(R.id.shadow_content);
    View frags = findViewById(R.id.main_content);
    View wkt = findViewById(R.id.webkit_view);
    shadow.setVisibility(View.GONE);
    shadow.removeAllViews();
    if (newFragment == ScreenList.WEBKIT) {
        frags.setVisibility(View.GONE);
        wkt.setVisibility(View.VISIBLE);
        wkt.invalidate();
    } else {
        wkt.setVisibility(View.GONE);
        frags.setVisibility(View.VISIBLE);
    }

    currentFragment = newFragment;
    BackStackEntry entry = null;
    for (int i = 0; i < mgr.getBackStackEntryCount(); ++i) {
        BackStackEntry e = mgr.getBackStackEntryAt(i);
        if (e.getName().equals(currentFragment.name())) {
            entry = e;
            break;
        }
    }
    if (entry != null) {
        // flush backward, including the screen want to go back to
        mgr.popBackStackImmediate(currentFragment.name(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

    // add transaction to show the screen we want
    FragmentTransaction trans = mgr.beginTransaction();
    trans.replace(R.id.main_content, f);
    trans.addToBackStack(currentFragment.name());
    trans.commit();

    // and see if we should re-initialize...
    if ((currentFragment != ScreenList.INITIALIZATION_DIALOG)
            && Survey.getInstance().shouldRunInitializationTask(getAppName())) {
        WebLogger.getLogger(getAppName()).i(t, "swapToFragmentView -- calling clearRunInitializationTask");
        // and immediately clear the should-run flag...
        Survey.getInstance().clearRunInitializationTask(getAppName());
        // OK we should swap to the InitializationFragment view
        swapToFragmentView(ScreenList.INITIALIZATION_DIALOG);
    } else {
        levelSafeInvalidateOptionsMenu();
    }
}