Example usage for android.app FragmentTransaction add

List of usage examples for android.app FragmentTransaction add

Introduction

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

Prototype

public abstract FragmentTransaction add(@IdRes int containerViewId, Fragment fragment, String tag);

Source Link

Document

Add a fragment to the activity state.

Usage

From source file:com.android.dialer.DialtactsFragment.java

/**
 * Initiates a fragment transaction to show the dialpad fragment. Animations and other visual
 * updates are handled by a callback which is invoked after the dialpad fragment is shown.
 * @see #onDialpadShown/*from   ww  w. j a  va  2 s .c om*/
 */
public void showDialpadFragment(boolean animate) {

    //        if (mIsDialpadShown || mStateSaved) {
    //            return;
    //        }
    if (mIsDialpadShown || mStateSaved || mDialpadFragment == null) {
        Log.e("showDialpadFragment ", " return; ");
        return;
    }
    mIsDialpadShown = true;
    animate = false;
    mDialpadFragment.setAnimate(animate);
    //        mListsFragment.setUserVisibleHint(false);
    AnalyticsUtil.sendScreenView(mDialpadFragment);

    final FragmentTransaction ft = getChildFragmentManager().beginTransaction();
    //if (mDialpadFragment == null) {
    //mDialpadFragment = new DialpadFragment();
    //  ft.add(R.id.dialtacts_container, mDialpadFragment, TAG_DIALPAD_FRAGMENT);
    //} else {
    ft.show(mDialpadFragment);
    //}

    //        mDialpadFragment.setAnimate(animate);

    //        ft.commit();

    //        if (animate) {
    ////            mFloatingActionButtonController.scaleOut();
    //        } else {
    ////            mFloatingActionButtonController.setVisible(false);
    //            maybeEnterSearchUi();
    //        }
    if (!isInSearchUi() && TextUtils.isEmpty(mSearchQuery)) {
        if (getCallLogFragment() == null) {
            mCalllogList = new CallLogFragment(CallLogQueryHandler.CALL_TYPE_ALL);
            mCalllogList.setRecyclerViewChangedImpl(mRecyclerViewChangedImpl);
            ft.add(R.id.dialtacts_frame, mCalllogList, "mCalllogList");
            ft.show(mCalllogList);
        } else {
            if (mSearchViewShow)
                mDialpadFragment.showSearchView();
            else
                mDialpadFragment.hideSearchView();
        }
    }
    ft.commitAllowingStateLoss();
    sendMessageToReflushEditerView();
    Log.e(TAG, " showDialpadFragment mIsDialpadShown:" + mIsDialpadShown + "  mInDialpadSearch:"
            + mInDialpadSearch + "  isDialpadShown() :" + isDialpadShown());

    //        mListsFragment.getView().animate().alpha(0).withLayer();
}

From source file:org.opendatakit.tables.activities.TableDisplayActivity.java

public void showDetailFragment(boolean createNew) {
    this.setCurrentFragmentType(ViewFragmentType.DETAIL);
    this.updateChildViewVisibility(ViewFragmentType.DETAIL);
    FragmentManager fragmentManager = this.getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    this.hideAllOtherViewFragments(ViewFragmentType.DETAIL, fragmentTransaction);
    String fileName = IntentUtil.retrieveFileNameFromBundle(this.getIntent().getExtras());
    // Try and use the default.
    if (fileName == null) {
        WebLogger.getLogger(getAppName()).d(TAG, "[showDetailFragment] fileName not found in Intent");
        SQLiteDatabase db = null;//from w ww  .j  a  v  a  2s.c  om
        try {
            db = DatabaseFactory.get().getDatabase(this, getAppName());
            fileName = TableUtil.get().getDetailViewFilename(db, getTableId());
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }
    String rowId = IntentUtil.retrieveRowIdFromBundle(this.getIntent().getExtras());
    // Try to retrieve one that already exists.
    DetailViewFragment detailViewFragment = (DetailViewFragment) fragmentManager
            .findFragmentByTag(Constants.FragmentTags.DETAIL_FRAGMENT);
    if (detailViewFragment == null || createNew) {
        if (detailViewFragment != null) {
            WebLogger.getLogger(getAppName()).d(TAG,
                    "[showDetailViewFragment] removing old detail view fragment");
            fragmentTransaction.remove(detailViewFragment);
        } else {
            WebLogger.getLogger(getAppName()).d(TAG,
                    "[showDetailViewFragment] no existing detail view fragment found");
        }
        detailViewFragment = this.createDetailViewFragment(fileName, rowId);

        fragmentTransaction.add(R.id.activity_table_display_activity_one_pane_content, detailViewFragment,
                Constants.FragmentTags.DETAIL_FRAGMENT);
    } else {
        WebLogger.getLogger(getAppName()).d(TAG,
                "[showDetailViewFragment] existing detail view fragment found");
        fragmentTransaction.show(detailViewFragment);
    }

    fragmentTransaction.commit();
}

From source file:com.android.dialer.DialtactsActivity.java

/**
 * Shows the search fragment//ww  w. j  a  va 2s .co m
 */
private void enterSearchUi(boolean smartDialSearch, String query, boolean animate) {
    if (mStateSaved || getFragmentManager().isDestroyed()) {
        // Weird race condition where fragment is doing work after the activity is destroyed
        // due to talkback being on (b/10209937). Just return since we can't do any
        // constructive here.
        return;
    }

    if (DEBUG) {
        Log.d(TAG, "Entering search UI - smart dial " + smartDialSearch);
    }

    final FragmentTransaction transaction = getFragmentManager().beginTransaction();
    if (mInDialpadSearch && mSmartDialSearchFragment != null) {
        transaction.remove(mSmartDialSearchFragment);
    } else if (mInRegularSearch && mRegularSearchFragment != null) {
        transaction.remove(mRegularSearchFragment);
    }

    final String tag;
    if (smartDialSearch) {
        tag = TAG_SMARTDIAL_SEARCH_FRAGMENT;
    } else {
        tag = TAG_REGULAR_SEARCH_FRAGMENT;
    }
    mInDialpadSearch = smartDialSearch;
    mInRegularSearch = !smartDialSearch;

    mFloatingActionButtonController.scaleOut();

    SearchFragment fragment = (SearchFragment) getFragmentManager().findFragmentByTag(tag);
    if (animate) {
        transaction.setCustomAnimations(android.R.animator.fade_in, 0);
    } else {
        transaction.setTransition(FragmentTransaction.TRANSIT_NONE);
    }
    if (fragment == null) {
        if (smartDialSearch) {
            fragment = new SmartDialSearchFragment();
        } else {
            fragment = ObjectFactory.newRegularSearchFragment();
            fragment.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // Show the FAB when the user touches the lists fragment and the soft
                    // keyboard is hidden.
                    hideDialpadFragment(true, false);
                    showFabInSearchUi();
                    return false;
                }
            });
        }
        transaction.add(R.id.dialtacts_frame, fragment, tag);
    } else {
        transaction.show(fragment);
    }
    // DialtactsActivity will provide the options menu
    fragment.setHasOptionsMenu(false);
    fragment.setShowEmptyListForNullQuery(true);
    if (!smartDialSearch) {
        fragment.setQueryString(query, false /* delaySelection */);
    }
    transaction.commit();

    if (animate) {
        mListsFragment.getView().animate().alpha(0).withLayer();
    }
    mListsFragment.setUserVisibleHint(false);

    if (smartDialSearch) {
        Logger.logScreenView(ScreenEvent.SMART_DIAL_SEARCH, this);
    } else {
        Logger.logScreenView(ScreenEvent.REGULAR_SEARCH, this);
    }
}

From source file:com.android.dialer.DialtactsFragment.java

/**
 * Shows the search fragment/*from w  ww.  j  a  v a2  s  .com*/
 */
private void enterSearchUi(boolean smartDialSearch, String query, boolean animate) {
    if (mStateSaved || getChildFragmentManager().isDestroyed()) {
        // Weird race condition where fragment is doing work after the activity is destroyed
        // due to talkback being on (b/10209937). Just return since we can't do any
        // constructive here.
        return;
    }
    mDialpadFragment.showSearchView();

    if (DEBUG) {
        Log.d(TAG, "Entering search UI - smart dial " + smartDialSearch);
    }

    final FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    if (mInDialpadSearch && mSmartDialSearchFragment != null) {
        transaction.remove(mSmartDialSearchFragment);
    } else if (mInRegularSearch && mRegularSearchFragment != null) {
        transaction.remove(mRegularSearchFragment);
    }

    final String tag;
    if (smartDialSearch) {
        tag = TAG_SMARTDIAL_SEARCH_FRAGMENT;
    } else {
        tag = TAG_REGULAR_SEARCH_FRAGMENT;
    }
    mInDialpadSearch = smartDialSearch;
    mInRegularSearch = !smartDialSearch;

    mFloatingActionButtonController.scaleOut();

    SearchFragment fragment = (SearchFragment) getChildFragmentManager().findFragmentByTag(tag);
    if (animate) {
        transaction.setCustomAnimations(android.R.animator.fade_in, 0);
    } else {
        transaction.setTransition(FragmentTransaction.TRANSIT_NONE);
    }
    if (fragment == null) {

        Log.e(TAG, " --- enterSearchUi --- null");
        if (smartDialSearch) {
            fragment = new SmartDialSearchFragment();
            transaction.add(R.id.dialtacts_frame, fragment, tag);
        } else {
            fragment = new RegularSearchFragment();
            fragment.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // Show the FAB when the user touches the lists fragment and the soft
                    // keyboard is hidden.
                    showFabInSearchUi();
                    return false;
                }
            });
        }

    } else {
        transaction.show(fragment);

    }
    // DialtactsFragment will provide the options menu
    fragment.setHasOptionsMenu(false);
    fragment.setShowEmptyListForNullQuery(true);
    fragment.setQueryString(query, false /* delaySelection */);
    transaction.commitAllowingStateLoss();
    //        transaction.commit();

    //        if (animate) {
    //            mListsFragment.getView().animate().alpha(0).withLayer();
    //        }
    //        mListsFragment.setUserVisibleHint(false);
}

From source file:com.android.contacts.activities.PeopleActivity.java

private void createViewsAndFragments(Bundle savedState) {
    // Disable the ActionBar so that we can use a Toolbar. This needs to be called before
    // setContentView().
    getWindow().requestFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.people_activity);

    final FragmentManager fragmentManager = getFragmentManager();

    // Hide all tabs (the current tab will later be reshown once a tab is selected)
    final FragmentTransaction transaction = fragmentManager.beginTransaction();

    mTabTitles = new String[TabState.COUNT];
    mTabTitles[TabState.FAVORITES] = getString(R.string.favorites_tab_label);
    mTabTitles[TabState.ALL] = getString(R.string.all_contacts_tab_label);
    mTabPager = getView(R.id.tab_pager);
    mTabPagerAdapter = new TabPagerAdapter();
    mTabPager.setAdapter(mTabPagerAdapter);
    mTabPager.setOnPageChangeListener(mTabPagerListener);

    // Configure toolbar and toolbar tabs. If in landscape mode, we  configure tabs differntly.
    final Toolbar toolbar = getView(R.id.toolbar);
    setActionBar(toolbar);/*from w ww  .  j  av a  2s.  co  m*/
    final ViewPagerTabs portraitViewPagerTabs = (ViewPagerTabs) findViewById(R.id.lists_pager_header);
    ViewPagerTabs landscapeViewPagerTabs = null;
    if (portraitViewPagerTabs == null) {
        landscapeViewPagerTabs = (ViewPagerTabs) getLayoutInflater()
                .inflate(R.layout.people_activity_tabs_lands, toolbar, /* attachToRoot = */ false);
        mViewPagerTabs = landscapeViewPagerTabs;
    } else {
        mViewPagerTabs = portraitViewPagerTabs;
    }
    mViewPagerTabs.setViewPager(mTabPager);

    final String FAVORITE_TAG = "tab-pager-favorite";
    final String ALL_TAG = "tab-pager-all";

    // Create the fragments and add as children of the view pager.
    // The pager adapter will only change the visibility; it'll never create/destroy
    // fragments.
    // However, if it's after screen rotation, the fragments have been re-created by
    // the fragment manager, so first see if there're already the target fragments
    // existing.
    mFavoritesFragment = (ContactTileListFragment) fragmentManager.findFragmentByTag(FAVORITE_TAG);
    mAllFragment = (MultiSelectContactsListFragment) fragmentManager.findFragmentByTag(ALL_TAG);

    if (mFavoritesFragment == null) {
        mFavoritesFragment = new ContactTileListFragment();
        mAllFragment = new MultiSelectContactsListFragment();

        transaction.add(R.id.tab_pager, mFavoritesFragment, FAVORITE_TAG);
        transaction.add(R.id.tab_pager, mAllFragment, ALL_TAG);
    }

    mFavoritesFragment.setListener(mFavoritesFragmentListener);

    mAllFragment.setOnContactListActionListener(new ContactBrowserActionListener());
    mAllFragment.setCheckBoxListListener(new CheckBoxListListener());

    // Hide all fragments for now.  We adjust visibility when we get onSelectedTabChanged()
    // from ActionBarAdapter.
    transaction.hide(mFavoritesFragment);
    transaction.hide(mAllFragment);

    transaction.commitAllowingStateLoss();
    fragmentManager.executePendingTransactions();

    // Setting Properties after fragment is created
    mFavoritesFragment.setDisplayType(DisplayType.STREQUENT);

    mActionBarAdapter = new ActionBarAdapter(this, this, getActionBar(), portraitViewPagerTabs,
            landscapeViewPagerTabs, toolbar);
    mActionBarAdapter.initialize(savedState, mRequest);

    // Add shadow under toolbar
    ViewUtil.addRectangularOutlineProvider(findViewById(R.id.toolbar_parent), getResources());

    // Configure floating action button
    mFloatingActionButtonContainer = findViewById(R.id.floating_action_button_container);
    final ImageButton floatingActionButton = (ImageButton) findViewById(R.id.floating_action_button);
    floatingActionButton.setOnClickListener(this);
    mFloatingActionButtonController = new FloatingActionButtonController(this, mFloatingActionButtonContainer,
            floatingActionButton);
    initializeFabVisibility();

    invalidateOptionsMenuIfNeeded();
}

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

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

    // Get preferences
    getSettings();//from  ww  w . j  a va  2  s .com

    // 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<ObjectDrawerItem> serverItems = new ArrayList<ObjectDrawerItem>();
    ArrayList<ObjectDrawerItem> actionItems = new ArrayList<ObjectDrawerItem>();
    ArrayList<ObjectDrawerItem> settingsItems = new ArrayList<ObjectDrawerItem>();

    // Add server category
    serverItems.add(new ObjectDrawerItem(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++) {
        //            Log.d("Debug", "MainActivity - currentServerValue - currentServerValue: " + currentServerValue);
        //            Log.d("Debug", "MainActivity - currentServerValue - (i + 1): " + (i + 1));
        //            Log.d("Debug", "MainActivity - currentServerValue - (i + 1) == currentServerValue: " + ((i + 1) == currentServerValue));

        serverItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_subitem, navigationDrawerServerItems[i],
                DRAWER_ITEM_SERVERS, ((i + 1) == currentServerValue), "changeCurrentServer"));

    }

    //
    //        serverItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_subitem, "Server 1", DRAWER_ITEM_SERVERS, true, "changeCurrentServer"));
    //        serverItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_subitem, "Server 2", DRAWER_ITEM_SERVERS, false, "changeCurrentServer"));
    //        serverItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_subitem, "Server 3", DRAWER_ITEM_SERVERS, false, "changeCurrentServer"));

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

    // Add settings actions
    //        drawerItems.add(new ObjectDrawerItem(R.drawable.ic_action_options, navigationDrawerItemTitles[6], DRAWER_ITEM_ACTIONS, false, "openOptions"));
    settingsItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_settings, navigationDrawerItemTitles[6],
            DRAWER_ITEM_ACTIONS, false, "openSettings"));
    if (packageName.equals("com.lgallardo.youtorrentcontroller")) {
        settingsItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_pro, navigationDrawerItemTitles[7],
                DRAWER_ITEM_ACTIONS, false, "getPro"));
        settingsItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_help, navigationDrawerItemTitles[8],
                DRAWER_ITEM_ACTIONS, false, "openHelp"));
    } else {
        settingsItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_help, navigationDrawerItemTitles[7],
                DRAWER_ITEM_ACTIONS, false, "openHelp"));
    }

    // Set adapter

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

    //        Log.d("Debug", "MainActivity - oldActionPosition: "+ (Arrays.asList(actionStates).indexOf(lastState)));

    //        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);

    // Set the item click listener
    //        drawerList.setOnItemClickListener(new DrawerItemClickListener());

    // 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);
    //        drawerToggle.syncState();               // Finally we set the drawer toggle sync State

    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 were awaked from an intent-filter,
    // Get token and cookie and then
    // get intent from the intent filter and Add URL torrent
    //        Log.d("Debug", "MainActivity - 1");
    new torrentTokenByIntent().execute(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.youtorrentcontroller.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.youtorrentcontroller.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.youtorrentcontroller.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.lgallardo.qbittorrentclient.RefreshListener.java

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

    // Get preferences
    getSettings();/*  w w  w.  ja v  a 2  s.  com*/

    // 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();

}