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.tassadar.multirommgr.MainActivity.java

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

    if (Build.VERSION.SDK_INT == 20) {
        showDeprecatedLAlert();/* w  w  w  .  jav a 2s.  c  o m*/
        return;
    }

    setContentView(R.layout.activity_main);

    // This activity is using different background color, which would cause overdraw
    // of the whole area, so disable the default background
    getWindow().setBackgroundDrawable(null);

    Utils.installHttpCache(this);
    PreferenceManager.setDefaultValues(this, R.xml.settings, false);

    m_srLayout = (MultiROMSwipeRefreshLayout) findViewById(R.id.refresh_layout);
    m_srLayout.setOnRefreshListener(this);

    m_curFragment = -1;

    m_fragmentTitles = getResources().getStringArray(R.array.main_fragment_titles);
    m_drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    m_drawerList = (ListView) findViewById(R.id.left_drawer);

    String[] fragmentClsNames = new String[MainFragment.MAIN_FRAG_CNT];
    for (int i = 0; i < fragmentClsNames.length; ++i)
        fragmentClsNames[i] = MainFragment.getFragmentClass(i).getName();

    m_fragments = new MainFragment[MainFragment.MAIN_FRAG_CNT];
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction t = fragmentManager.beginTransaction();
    for (int i = 0; i < m_fragments.length; ++i) {
        m_fragments[i] = (MainFragment) fragmentManager.findFragmentByTag(fragmentClsNames[i]);
        if (m_fragments[i] == null) {
            m_fragments[i] = MainFragment.newFragment(i);
            t.add(R.id.content_frame, m_fragments[i], fragmentClsNames[i]);
        }
        t.hide(m_fragments[i]);
    }
    t.commit();

    // Set the adapter for the list view
    m_drawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, m_fragmentTitles));
    // Set the list's click listener
    m_drawerList.setOnItemClickListener(new DrawerItemClickListener());

    m_drawerTitle = getText(R.string.app_name);
    m_drawerToggle = new ActionBarDrawerToggle(this, m_drawerLayout, R.string.drawer_open,
            R.string.drawer_close) {
        public void onDrawerClosed(View view) {
            getSupportActionBar().setTitle(m_title);
        }

        public void onDrawerOpened(View drawerView) {
            getSupportActionBar().setTitle(m_drawerTitle);
        }
    };
    m_drawerLayout.setDrawerListener(m_drawerToggle);

    final ActionBar bar = getSupportActionBar();
    if (bar != null) {
        bar.setDisplayHomeAsUpEnabled(true);
        bar.setHomeButtonEnabled(true);
    }

    if (getIntent().hasExtra(INTENT_EXTRA_SHOW_ROM_LIST)
            && getIntent().getBooleanExtra(INTENT_EXTRA_SHOW_ROM_LIST, false)) {
        getIntent().removeExtra(INTENT_EXTRA_SHOW_ROM_LIST);
        selectItem(1);
    } else if (savedInstanceState != null) {
        selectItem(savedInstanceState.getInt("curFragment", 0));
    } else {
        selectItem(0);
    }
}

From source file:com.evandroid.musica.MainLyricActivity.java

public void updateLyricsFragment(int outAnim, String... params) { // Should only be called from SearchFragment or IdDecoder
    String artist = params[0];//from w  w  w . j a  v  a  2 s.c o m
    String song = params[1];
    String url = null;
    if (params.length > 2)
        url = params[2];
    LyricsViewFragment lyricsViewFragment = (LyricsViewFragment) getFragmentManager()
            .findFragmentByTag(LYRICS_FRAGMENT_TAG);
    if (lyricsViewFragment != null)
        lyricsViewFragment.fetchLyrics(artist, song, url);
    else {
        Lyrics lyrics = new Lyrics(Lyrics.SEARCH_ITEM);
        lyrics.setArtist(artist);
        lyrics.setTitle(song);
        lyrics.setURL(url);
        Bundle lyricsBundle = new Bundle();
        try {
            if (artist != null && song != null)
                lyricsBundle.putByteArray("lyrics", lyrics.toBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        lyricsViewFragment = new LyricsViewFragment();
        lyricsViewFragment.setArguments(lyricsBundle);

        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        Fragment activeFragment = getDisplayedFragment(getActiveFragments());
        if (activeFragment != null) {
            prepareAnimations(activeFragment);
            fragmentTransaction.hide(activeFragment);
        }
        fragmentTransaction.add(R.id.main_fragment_container, lyricsViewFragment, LYRICS_FRAGMENT_TAG);
        lyricsViewFragment.isActiveFragment = true;
        fragmentTransaction.commit();
    }
}

From source file:com.zte.permissioncontrol.ui.PermissionControlPageActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.permission_control_pages);
    mEmptyView = (FrameLayout) findViewById(R.id.empty_view);
    mSavedInstanceState = savedInstanceState;
    // add the switch on Action bar
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mSwitch = (Switch) inflater.inflate(R.layout.imageswitch_layout, null);
    final int padding = getResources().getDimensionPixelSize(R.dimen.action_bar_switch_padding);
    mSwitch.setPadding(0, 0, padding, 0);
    getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM, ActionBar.DISPLAY_SHOW_CUSTOM);
    getActionBar().setCustomView(mSwitch, new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,
            ActionBar.LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.END));
    mSwitch.setOnCheckedChangeListener(this);

    // hide fragment firstly , then update it in onResume() according to switch status
    final FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();

    mPermissionsFragment = (PermissionsFragment) fragmentManager.findFragmentByTag(mPermissionsTag);
    mAppsFragment = (AppsFragment) fragmentManager.findFragmentByTag(mAppsTag);

    if (mPermissionsFragment == null) {
        mPermissionsFragment = new PermissionsFragment();
        mAppsFragment = new AppsFragment();
        transaction.add(R.id.tab_pager, mPermissionsFragment, mPermissionsTag);
        transaction.add(R.id.tab_pager, mAppsFragment, mAppsTag);
    }/*from  ww w .ja va2  s.c o  m*/

    transaction.hide(mPermissionsFragment);
    transaction.hide(mAppsFragment);
    transaction.commit();
    fragmentManager.executePendingTransactions();

    // set page adapter
    mTabPager = (ViewPager) findViewById(R.id.tab_pager);
    mTabPagerAdapter = new TabPagerAdapter();
    mTabPager.setAdapter(mTabPagerAdapter);
    mTabPager.setOnPageChangeListener(mTabPagerListener);

    // Configure action bar
    mActionBarAdapter = new ActionBarAdapter(this, this, getActionBar());

    boolean isShow = PermControlUtils.isPermControlOn(this);
    Log.d(TAG, "oncreate(), isShow " + isShow);

}

From source file:com.android.contacts.detail.ContactDetailLayoutController.java

private void initialize(Bundle savedState) {
    boolean fragmentsAddedToFragmentManager = true;
    mDetailFragment = (ContactDetailFragment) mFragmentManager
            .findFragmentByTag(ContactDetailViewPagerAdapter.ABOUT_FRAGMENT_TAG);
    mUpdatesFragment = (ContactDetailUpdatesFragment) mFragmentManager
            .findFragmentByTag(ContactDetailViewPagerAdapter.UPDATES_FRAGMENT_TAG);

    // If the detail fragment was found in the {@link FragmentManager} then we don't need to add
    // it again. Otherwise, create the fragments dynamically and remember to add them to the
    // {@link FragmentManager}.
    if (mDetailFragment == null) {
        mDetailFragment = new ContactDetailFragment();
        mUpdatesFragment = new ContactDetailUpdatesFragment();
        fragmentsAddedToFragmentManager = false;
    }/*  ww  w.j  a  v a2  s.  com*/

    mDetailFragment.setListener(mContactDetailFragmentListener);
    NfcHandler.register(mActivity, mDetailFragment);

    // Read from savedState if possible
    int currentPageIndex = 0;
    if (savedState != null) {
        mContactUri = savedState.getParcelable(KEY_CONTACT_URI);
        mContactHasUpdates = savedState.getBoolean(KEY_CONTACT_HAS_UPDATES);
        currentPageIndex = savedState.getInt(KEY_CURRENT_PAGE_INDEX, 0);
    }

    switch (mLayoutMode) {
    case LayoutMode.VIEW_PAGER_AND_TAB_CAROUSEL: {
        // Inflate 2 view containers to pass in as children to the {@link ViewPager},
        // which will in turn be the parents to the mDetailFragment and mUpdatesFragment
        // since the fragments must have the same parent view IDs in both landscape and
        // portrait layouts.
        mDetailFragmentView = mLayoutInflater.inflate(R.layout.contact_detail_about_fragment_container,
                mViewPager, false);
        mUpdatesFragmentView = mLayoutInflater.inflate(R.layout.contact_detail_updates_fragment_container,
                mViewPager, false);

        mViewPagerAdapter = new ContactDetailViewPagerAdapter();
        mViewPagerAdapter.setAboutFragmentView(mDetailFragmentView);
        mViewPagerAdapter.setUpdatesFragmentView(mUpdatesFragmentView);

        mViewPager.addView(mDetailFragmentView);
        mViewPager.addView(mUpdatesFragmentView);
        mViewPager.setAdapter(mViewPagerAdapter);
        mViewPager.setOnPageChangeListener(mOnPageChangeListener);

        if (!fragmentsAddedToFragmentManager) {
            FragmentTransaction transaction = mFragmentManager.beginTransaction();
            transaction.add(R.id.about_fragment_container, mDetailFragment,
                    ContactDetailViewPagerAdapter.ABOUT_FRAGMENT_TAG);
            transaction.add(R.id.updates_fragment_container, mUpdatesFragment,
                    ContactDetailViewPagerAdapter.UPDATES_FRAGMENT_TAG);
            transaction.commitAllowingStateLoss();
            mFragmentManager.executePendingTransactions();
        }

        mTabCarousel.setListener(mTabCarouselListener);
        mTabCarousel.restoreCurrentTab(currentPageIndex);
        mDetailFragment.setVerticalScrollListener(new VerticalScrollListener(TAB_INDEX_DETAIL));
        mUpdatesFragment.setVerticalScrollListener(new VerticalScrollListener(TAB_INDEX_UPDATES));
        mViewPager.setCurrentItem(currentPageIndex);
        break;
    }
    case LayoutMode.TWO_COLUMN: {
        if (!fragmentsAddedToFragmentManager) {
            FragmentTransaction transaction = mFragmentManager.beginTransaction();
            transaction.add(R.id.about_fragment_container, mDetailFragment,
                    ContactDetailViewPagerAdapter.ABOUT_FRAGMENT_TAG);
            transaction.add(R.id.updates_fragment_container, mUpdatesFragment,
                    ContactDetailViewPagerAdapter.UPDATES_FRAGMENT_TAG);
            transaction.commitAllowingStateLoss();
            mFragmentManager.executePendingTransactions();
        }
        break;
    }
    case LayoutMode.FRAGMENT_CAROUSEL:
    case LayoutMode.TWO_COLUMN_FRAGMENT_CAROUSEL: {
        // Add the fragments to the fragment containers in the carousel using a
        // {@link FragmentTransaction} if they haven't already been added to the
        // {@link FragmentManager}.
        if (!fragmentsAddedToFragmentManager) {
            FragmentTransaction transaction = mFragmentManager.beginTransaction();
            transaction.add(R.id.about_fragment_container, mDetailFragment,
                    ContactDetailViewPagerAdapter.ABOUT_FRAGMENT_TAG);
            transaction.add(R.id.updates_fragment_container, mUpdatesFragment,
                    ContactDetailViewPagerAdapter.UPDATES_FRAGMENT_TAG);
            transaction.commitAllowingStateLoss();
            mFragmentManager.executePendingTransactions();
        }

        mFragmentCarousel.setFragmentViews((FrameLayoutWithOverlay) mDetailFragmentView,
                (FrameLayoutWithOverlay) mUpdatesFragmentView);
        mFragmentCarousel.setCurrentPage(currentPageIndex);

        break;
    }
    }

    // Setup the layout if we already have a saved state
    if (savedState != null) {
        if (mContactHasUpdates) {
            showContactWithUpdates(false);
        } else {
            showContactWithoutUpdates();
        }
    }
}

From source file:com.github.chenxiaolong.dualbootpatcher.MainActivity.java

private void showFragment() {
    FragmentManager fm = getFragmentManager();

    Fragment prevRoms = fm.findFragmentByTag(SwitcherListFragment.TAG);
    Fragment prevPatchFile = fm.findFragmentByTag(PatchFileFragment.TAG);
    Fragment prevFreeSpace = fm.findFragmentByTag(FreeSpaceFragment.TAG);
    Fragment prevAbout = fm.findFragmentByTag(AboutFragment.TAG);

    FragmentTransaction ft = fm.beginTransaction();
    ft.setCustomAnimations(R.animator.fragment_in, 0);

    switch (mFragment) {
    case FRAGMENT_ROMS:
        mTitle = R.string.title_roms;//from  w  w w  . j a  v  a2 s .co m
        updateTitle();

        if (prevRoms == null) {
            Fragment f = SwitcherListFragment.newInstance();
            ft.add(R.id.content_frame, f, SwitcherListFragment.TAG);
        } else {
            ft.show(prevRoms);
        }

        break;

    case FRAGMENT_PATCH_FILE:
        mTitle = R.string.title_patch_zip;
        updateTitle();

        if (prevPatchFile == null) {
            Fragment f = PatchFileFragment.newInstance();
            ft.add(R.id.content_frame, f, PatchFileFragment.TAG);
        } else {
            ft.show(prevPatchFile);
        }

        break;

    case FRAGMENT_FREE_SPACE:
        mTitle = R.string.title_free_space;
        updateTitle();

        if (prevFreeSpace == null) {
            Fragment f = FreeSpaceFragment.newInstance();
            ft.add(R.id.content_frame, f, FreeSpaceFragment.TAG);
        } else {
            ft.show(prevFreeSpace);
        }

        break;

    case FRAGMENT_ABOUT:
        mTitle = BuildConfig.APP_NAME_RESOURCE;
        updateTitle();

        if (prevAbout == null) {
            Fragment f = AboutFragment.newInstance();
            ft.add(R.id.content_frame, f, AboutFragment.TAG);
        } else {
            ft.show(prevAbout);
        }

        break;

    default:
        throw new IllegalStateException("Invalid fragment ID");
    }

    ft.commit();
}

From source file:it.angrydroids.epub3reader.MainActivity.java

public void addPanel(SplitPanel p) {
    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
    fragmentTransaction.add(R.id.MainLayout, p, p.getTag());
    fragmentTransaction.commit();// ww  w  . j  a  v  a 2  s.c  om

    panelCount++;
}

From source file:com.zte.permissioncontrol.ui.PermissionControlPageActivity.java

protected void addUI() {
    Log.d(TAG, "addUI()");
    // must get a new transaction each time
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    // set empty view to gone
    mEmptyView.setVisibility(View.GONE);
    // add all the fragment
    mPermissionsFragment = (PermissionsFragment) getFragmentManager().findFragmentByTag(mPermissionsTag);
    mAppsFragment = (AppsFragment) getFragmentManager().findFragmentByTag(mAppsTag);

    if (mPermissionsFragment == null) {
        mPermissionsFragment = new PermissionsFragment();
        mAppsFragment = new AppsFragment();
        transaction.add(R.id.tab_pager, mPermissionsFragment, mPermissionsTag);
        transaction.add(R.id.tab_pager, mAppsFragment, mAppsTag);
    }/* w  w w .j  a v  a  2s  .co m*/
    transaction.show(mPermissionsFragment);
    transaction.show(mAppsFragment);

    transaction.commit();

    getFragmentManager().executePendingTransactions();
    // firstly remove tabs ,then add tabs and update it
    mActionBarAdapter.removeAllTab();
    mActionBarAdapter.addUpdateTab(mSavedInstanceState);
}

From source file:com.ht.app.RestaurantsActivity.java

@Override
protected void setupView() {

    mDrawerMenuTitles = new String[] { "Restaurants", "Masjid and Prayer Rooms", "Contact Us" };
    mDrawerMenuOnItemClickListener = new AdapterView.OnItemClickListener() {
        @Override/*from ww  w .ja  va 2s .  c o  m*/
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            if (position == 1) {
                Intent msjidIntent = new Intent(RestaurantsActivity.this, MasjidActivity.class);
                startActivity(msjidIntent);
                finish();
            } else if (position == 2) {
                Utils.showComposeEmailUI(RestaurantsActivity.this);

            }
        }
    };

    super.setupView(); // Setup left slide menu

    Utils.setStatusBarColor(this, getResources().getColor(R.color.app_red_color_dark));

    mListView = (ListView) findViewById(R.id.list);
    mListView.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
    mLoadingListAdapter = new LoadingListAdapter(this);
    mNoGPSAdapter = new NoGpsAdapter(this);
    mNoInterentConnectionAdapter = new NoInternetAdapter(this);

    mSlidingUpPanelLayout = (SlidingUpPanelLayout) findViewById(R.id.slidingLayout);
    mSlidingUpPanelLayout.setEnableDragViewTouchEvents(true);

    int mapHeight = getResources().getDimensionPixelSize(R.dimen.map_height);
    mSlidingUpPanelLayout.setPanelHeight(mapHeight); // you can use different height here
    mSlidingUpPanelLayout.setScrollableView(mListView, mapHeight);

    mSlidingUpPanelLayout.setPanelSlideListener(this);

    // transparent view at the top of ListView
    mTransparentView = findViewById(R.id.transparentView);

    // init header view for ListView
    mTransparentHeaderView = LayoutInflater.from(this).inflate(R.layout.transparent_header_view, null, false);
    mWhiteFooterView = LayoutInflater.from(this).inflate(R.layout.white_footer_view, null, false);
    mSpaceView = mTransparentHeaderView.findViewById(R.id.space);
    mListView.addHeaderView(mTransparentHeaderView);
    mListView.addFooterView(mWhiteFooterView);

    mListView.setAdapter(mLoadingListAdapter);
    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            mSlidingUpPanelLayout.collapsePane();
            Restaurant selectedRestaurant = (Restaurant) mListView.getItemAtPosition(position);
            showRestaurantDetailsActivity(selectedRestaurant);

        }
    });

    mMapFragment = MapFragment.newInstance();
    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
    fragmentTransaction.add(R.id.mapContainer, mMapFragment, "map");
    fragmentTransaction.commit();

    // Create a GoogleApiClient instance
    mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API)
            .addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
    setUpMapIfNeeded();

}

From source file:com.google.samples.apps.iosched.ui.SessionLivestreamActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_captions:
        if (mIsFullscreen) {
            if (mFullscreenCaptions.getVisibility() == View.GONE) {
                mFullscreenCaptions.setVisibility(View.VISIBLE);
                SessionCaptionsFragment captionsFragment;
                captionsFragment = (SessionCaptionsFragment) getFragmentManager()
                        .findFragmentByTag(TAG_CAPTIONS);
                if (captionsFragment == null) {
                    captionsFragment = new SessionCaptionsFragment();
                    captionsFragment.setDarkTheme(true);
                    FragmentTransaction ft = getFragmentManager().beginTransaction();
                    ft.add(R.id.fullscreen_captions, captionsFragment, TAG_CAPTIONS);
                    ft.commit();/*from w  w w.j av  a 2s  .  co  m*/
                }
                captionsFragment.updateViews(mCaptionsUrl);
                return true;
            }
        }
        mFullscreenCaptions.setVisibility(View.GONE);
        break;
    case R.id.menu_share:
        if (mSessionShareData != null) {
            new SessionsHelper(this).shareSession(this, R.string.share_livestream_template,
                    mSessionShareData.title, mSessionShareData.hashtag, mSessionShareData.sessionUrl);
            return true;
        }
        break;
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.saarang.samples.apps.iosched.ui.SessionLivestreamActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case com.saarang.samples.apps.iosched.R.id.menu_captions:
        if (mIsFullscreen) {
            if (mFullscreenCaptions.getVisibility() == View.GONE) {
                mFullscreenCaptions.setVisibility(View.VISIBLE);
                SessionCaptionsFragment captionsFragment;
                captionsFragment = (SessionCaptionsFragment) getFragmentManager()
                        .findFragmentByTag(TAG_CAPTIONS);
                if (captionsFragment == null) {
                    captionsFragment = new SessionCaptionsFragment();
                    captionsFragment.setDarkTheme(true);
                    FragmentTransaction ft = getFragmentManager().beginTransaction();
                    ft.add(com.saarang.samples.apps.iosched.R.id.fullscreen_captions, captionsFragment,
                            TAG_CAPTIONS);
                    ft.commit();/*w  w w . j av  a2s .  co m*/
                }
                captionsFragment.updateViews(mCaptionsUrl);
                return true;
            }
        }
        mFullscreenCaptions.setVisibility(View.GONE);
        break;
    case com.saarang.samples.apps.iosched.R.id.menu_share:
        if (mSessionShareData != null) {
            new SessionsHelper(this).shareSession(this,
                    com.saarang.samples.apps.iosched.R.string.share_livestream_template,
                    mSessionShareData.title, mSessionShareData.hashtag, mSessionShareData.sessionUrl);
            return true;
        }
        break;
    }
    return super.onOptionsItemSelected(item);
}