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:com.learnit.LearnIt.activities.MainActivity.java

public void onArticleSelected(int position) {
    // Create a new listOfFragments
    MySmartFragment fragment;/*from  www  .j a  va2 s .c  o m*/
    switch (position) {
    case ADD_WORDS_FRAGMENT:
        fragment = new AddWordFragment();
        fragment.identifier = ADD_WORDS_FRAGMENT;
        Log.d(LOG_TAG, "Created AddWordFragment with tag " + fragment.identifier);
        break;
    case DICTIONARY_FRAGMENT:
        fragment = new DictFragment();
        fragment.identifier = DICTIONARY_FRAGMENT;
        Log.d(LOG_TAG, "Created Dictionary Fragment with tag " + fragment.identifier);
        break;
    case LEARN_WORDS_FRAGMENT:
        fragment = new LearnCasualFragment();
        fragment.identifier = LEARN_WORDS_FRAGMENT;
        Log.d(LOG_TAG, "Created LearnFragment with tag " + fragment.identifier);
        break;
    default:
        fragment = null;
    }
    // Update the layout
    FragmentManager fm = getFragmentManager();

    if (fm.findFragmentByTag("android:switcher:" + 0 + ":" + position) == null) {
        FragmentTransaction ft = fm.beginTransaction();
        ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
        ft.replace(R.id.view_group_id, fragment, "android:switcher:" + 0 + ":" + position);
        Log.d(LOG_TAG, "current fragment id = " + fragment.getId() + " and tag = " + fragment.getTag()
                + ((Object) fragment).getClass().getName());
        ft.commit();
    }
    _currentItemShown = position;
    Log.d(LOG_TAG, "onArticleSelected current item set to " + _currentItemShown);
}

From source file:com.example.ogadrive.HomeActivity2.java

private void selectItem(int position) {
    // update the main content by replacing fragments
    Fragment fragment = null;/*from  w  w w .ja  v  a 2 s  .  co  m*/

    if (position == 1) {
        /*fragment = new HomeFragement();
        fragment.setArguments(bundle);*/

        fragment = new FragmentHistory();
        fragment.setArguments(bundle);
    } else if (position == 0) {
        fragment = new FragmentProfile();
        fragment.setArguments(bundle);

    } else if (position == 2) {

        setTitle("Contact Us");
    } else if (position == 3) {

        fragment = new FragmentHistory();
        fragment.setArguments(bundle);
    }

    if (fragment == null) {
        fragment = new HomeFragement();
        fragment.setArguments(bundle);
    }

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

    fragmentTransaction.add(R.id.content_frame, fragment);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
    // fragmentTransaction.addToBackStack("hradesh").commit();
    // fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount()-1);

    // update selected item and title, then close the drawer
    mDrawerList.setItemChecked(position, true);

    // }
    mDrawerLayout.closeDrawer(mDrawerList);
}

From source file:com.example.sans.myapplication.Login.OnlineActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_online);

    shares = getSharedPreferences("SHARES", 0);

    Fragment newFragment = new OnlineBotFragment();
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.login_bot, newFragment);
    transaction.addToBackStack(null);/*w  w w. ja  v  a2 s .  co m*/
    transaction.commit();

    transaction = getFragmentManager().beginTransaction();
    newFragment = new LoginTopFragment();
    transaction.replace(R.id.login_top, newFragment);
    transaction.commit();

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

    setSupportActionBar(toolbar);

    //Initializing NavigationView
    navigationView = (NavigationView) findViewById(R.id.navigation_view);

    //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu

    header = navigationView.inflateHeaderView(R.layout.header);
    JSONObject driver_data = null;
    try {
        driver_data = new JSONObject(shares.getString("DRIVER_DATA", "ERROR"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    TextView driver_name_header = (TextView) header.findViewById(R.id.username);
    TextView car_id_header = (TextView) header.findViewById(R.id.car_id);
    final ImageView pp_header = (ImageView) header.findViewById(R.id.profile_image);

    try {
        car_id_header.setText(driver_data.getString("license"));
        driver_name_header.setText(driver_data.getString("name"));
        Client client = new Client();
        client.get(driver_data.getString("image"),
                new FileAsyncHttpResponseHandler(OnlineActivity.this.getApplicationContext()) {
                    @Override
                    public void onFailure(int i, Header[] headers, Throwable throwable, File file) {

                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, final File response) {

                        OnlineActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Bitmap image = BitmapFactory.decodeFile(response.getPath());

                                pp_header.setImageBitmap(image);

                            }
                        });

                    }

                });
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        SharedPreferences.Editor editor = shares.edit();

        final Client client1 = new Client();
        RequestParams params1 = new RequestParams();

        editor.putBoolean("ONLINE", false);
        editor.putBoolean("LOGIN", false);
        editor.commit();
        Intent intent = getApplicationContext().getPackageManager()
                .getLaunchIntentForPackage(getApplicationContext().getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    header.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent i = new Intent(OnlineActivity.this, MenuItemActivity.class);
            i.putExtra("MENU_ITEM", 0);
            OnlineActivity.this.startActivity(i);
            drawerLayout.closeDrawers();
        }
    });

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        // This method will trigger on item Click of navigation menu
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            //Checking if the item is in checked state or not, if not make it in checked state

            nav = true;

            menuItem.setChecked(false);

            //Closing drawer on item click
            drawerLayout.closeDrawers();

            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            Fragment fragment;
            //Check to see which item was being clicked and perform appropriate action
            switch (menuItem.getItemId()) {
            case R.id.timetable:
            case R.id.service:
            case R.id.history:
            case R.id.mission:
            case R.id.points:
            case R.id.notice:
                Intent i = new Intent(OnlineActivity.this, MenuItemActivity.class);
                i.putExtra("MENU_ITEM", menuItem.getItemId());
                OnlineActivity.this.startActivity(i);
                break;
            case R.id.login:
                Toast.makeText(getApplicationContext(), "Logout Selected", Toast.LENGTH_SHORT).show();
                SharedPreferences.Editor editor = shares.edit();

                final Client client = new Client();
                RequestParams params = new RequestParams();
                params.put("id", shares.getInt("ID", 0));
                params.put("status", 999);
                client.post("driver/setStatus", params, new JsonHttpResponseHandler());

                editor.putBoolean("ONLINE", false);
                editor.putBoolean("LOGIN", false);
                editor.commit();
                Intent intent = getApplicationContext().getPackageManager()
                        .getLaunchIntentForPackage(getApplicationContext().getPackageName());
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
            default:
                Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
                break;

            }
            return false;
        }
    });

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.openDrawer, R.string.closeDrawer) {

        @Override
        public void onDrawerClosed(View drawerView) {
            // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
            super.onDrawerClosed(drawerView);
            drawerLayout.setSelected(false);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank

            super.onDrawerOpened(drawerView);
        }
    };

    drawerLayout.setDrawerListener(actionBarDrawerToggle);

    actionBarDrawerToggle.syncState();
}

From source file:it.gmariotti.cardslib.demo.extras.MainActivity.java

private void openFragment(BaseFragment baseFragment) {
    if (baseFragment != null) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        //fragmentTransaction.setCustomAnimations(R.animator.carddemo_fag_fade_in,R.animator.carddemo_frag_fade_out);

        fragmentTransaction.replace(R.id.fragment_main_extras, baseFragment);
        //fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();//ww w .j a v a  2  s.  c om
        if (baseFragment.getTitleResourceId() > 0)
            mCurrentTitle = baseFragment.getTitleResourceId();
    }
}

From source file:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.FetchReservationsToDate.java

/**
 * Clears adapter of current data and fills it with fetched reservations.
 * In process it clears details fragment, so it could not display information about no longer existing reservation.
 *
 * @param resultList fetched reservations
 *//* w  w  w .j a  va  2  s .  c o m*/
@Override
protected void onPostExecute(List<Reservation> resultList) {
    reservationAdapter.clear();
    if (resultList != null && !resultList.isEmpty()) {
        for (Reservation reservation : resultList) {
            try {
                reservationAdapter.add(reservation);
            } catch (Exception e) {
                setState(ERROR, e);
                Log.e(TAG, e.getLocalizedMessage(), e);
            }
        }
    }

    FragmentManager fm = activity.getFragmentManager();

    ReservationDetailsFragment details = new ReservationDetailsFragment();
    ReservationDetailsFragment frag = (ReservationDetailsFragment) fm
            .findFragmentByTag(ReservationDetailsFragment.TAG);
    if (frag != null) {
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.details, details, ReservationDetailsFragment.TAG);
        ft.commit();
    }
}

From source file:it.gmariotti.cardslib.demo.extras.MainActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.demo_extras_activity_main);

    // The attacher should always be created in the Activity's onCreate
    //mPullToRefreshAttacher = PullToRefreshAttacher.get(this);

    // enable ActionBar app icon to behave as action to toggle nav drawer
    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout_extras);

    mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

    _initMenu();// w  w w.ja  v a  2 s  .  co  m
    mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
    mDrawer.setDrawerListener(mDrawerToggle);

    // ---------------------------------------------------------------
    // ...
    String base64EncodedPublicKey = IabUtil.key;

    // compute your public key and store it in base64EncodedPublicKey
    mHelper = new IabHelper(this, base64EncodedPublicKey);
    mHelper.enableDebugLogging(true);

    mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
        public void onIabSetupFinished(IabResult result) {
            if (!result.isSuccess()) {
                // Oh noes, there was a problem.
                Log.d(TAG, "Problem setting up In-app Billing: " + result);
            }

            // Have we been disposed of in the meantime? If so, quit.
            if (mHelper == null)
                return;

            // Hooray, IAB is fully set up!
            IabUtil.getInstance().retrieveData(mHelper);
        }
    });
    //-----------------------------------------------------------------
    //BaseFragment baseFragment = null;
    if (savedInstanceState != null) {
        mSelectedFragment = savedInstanceState.getInt(BUNDLE_SELECTEDFRAGMENT);

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (fragmentManager.findFragmentById(R.id.fragment_main_extras) == null)
            mBaseFragment = selectFragment(mSelectedFragment);
        //if (mBaseFragment==null)
        //    mBaseFragment = selectFragment(mSelectedFragment);
    } else {
        mBaseFragment = new PicassoFragment();
        openFragment(mBaseFragment);
    }

    //-----------------------------------------------------------------
}

From source file:com.devnoobs.bmr.MainActivity.java

private void selectItem(int position) {
    // update the main content by replacing fragments

    if (position == 0) {
        Fragment bmr = (Fragment) new FragmentBMR();
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, bmr).commit();
    } else if (position == 1) {
        Fragment tabele = (Fragment) new FragmentTabele();
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, tabele).commit();
    } else if (position == 2) {
        Fragment wykresy = (Fragment) new FragmentWykres();
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, wykresy).commit();
    } else if (position == 3) {
        Fragment ustawienia = (Fragment) new FragmentUstawienia();
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, ustawienia).commit();
    }/* w  ww  .jav a2s.  c o  m*/

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

}

From source file:com.pgmacdesign.lacunacompanion.MainActivity.java

private void displayView(int position) {
    //Update the main content by replacing fragments
    Fragment fragment = null;/*from w w w. j av a  2  s.  c  om*/

    switch (position) {
    case 0:
        fragment = new HomeFragment();
        break;

    case 1:
        fragment = new LogOutInFragment();
        break;

    case 2:
        fragment = new MailFragment();
        break;

    case 3:
        fragment = new UpgradeBuildQueueFragment();
        break;

    case 4:
        fragment = new ListPlanetsFragment();
        break;
    case 5:
        fragment = new WebLinksFragment();
        break;

    case 6:
        fragment = new ShipsFragment();
        break;

    case 7:
        fragment = new BuildingFragment();
        break;

    case 8:
        fragment = new LookupPlanetFragment();
        break;

    case 9:
        fragment = new OrbitXYCalculatorFragment();
        break;

    case 10:
        fragment = new DistanceCalculatorFragment();
        break;

    case 11:
        fragment = new SitterPWManagerFragment();
        break;

    case 12:
        fragment = new SettingsPreferencesFragment();
        break;

    case 13:
        fragment = new AboutUsCreditsFragment();
        break;

    case 14:
        fragment = new DonateFragment();
        break;

    case 15:
        finish();
        break;

    default:
        break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();

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

    } else {
        //Fragment could not be created
        L.m("MainActivity", "Error in creating fragment");
    }
}

From source file:de.sourcestream.movieDB.controller.CastDetailsInfo.java

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    activity.getCastDetailsFragment().showInstantToolbar();
    activity.setCastDetailsFragment(null);
    activity.setRestoreMovieDetailsAdapterState(true);
    activity.setRestoreMovieDetailsState(false);

    if (knownList.get(position).getMediaType().equals("movie")) {
        if (activity.getMovieDetailsFragment() != null
                && activity.getLastVisitedMovieInCredits() == knownList.get(position).getId()
                && activity.getMovieDetailsFragment().getTimeOut() == 0) {
            // Old movie details retrieve info and re-init component else crash
            activity.getMovieDetailsFragment().onSaveInstanceState(new Bundle());
            Bundle bundle = new Bundle();
            bundle.putInt("id", knownList.get(position).getId());
            Bundle save = activity.getMovieDetailsFragment().getSave();
            // Re-init movie details and set save information
            movieDetails = new MovieDetails();
            movieDetails.setTimeOut(0);/*  ww w  . j av a 2s  . c  o m*/
            movieDetails.setSave(save);
            movieDetails.setArguments(bundle);
        } else
            movieDetails = new MovieDetails();
    }

    if (knownList.get(position).getMediaType().equals("tv")) {
        if (activity.getTvDetailsFragment() != null
                && activity.getLastVisitedMovieInCredits() == knownList.get(position).getId()
                && activity.getTvDetailsFragment().getTimeOut() == 0) {
            // Old movie details retrieve info and re-init component else crash
            activity.getTvDetailsFragment().onSaveInstanceState(new Bundle());
            Bundle bundle = new Bundle();
            bundle.putInt("id", knownList.get(position).getId());
            Bundle save = activity.getTvDetailsFragment().getSave();
            // Re-init movie details and set save information
            tvDetails = new TVDetails();
            tvDetails.setTimeOut(0);
            tvDetails.setSave(save);
            tvDetails.setArguments(bundle);
        } else
            tvDetails = new TVDetails();
    }

    activity.setLastVisitedMovieInCredits(knownList.get(position).getId());
    ((CastDetails) getParentFragment()).setAddToBackStack(true);
    getParentFragment().onSaveInstanceState(new Bundle());
    if (activity.getSearchViewCount())
        activity.incSearchCastDetails();

    FragmentManager manager = getActivity().getFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    Bundle bundle = new Bundle();
    bundle.putInt("id", knownList.get(position).getId());

    if (knownList.get(position).getMediaType().equals("movie")) {
        movieDetails.setTitle(knownList.get(position).getTitle());
        movieDetails.setArguments(bundle);
        transaction.replace(R.id.frame_container, movieDetails);
    }
    if (knownList.get(position).getMediaType().equals("tv")) {
        tvDetails.setTitle(knownList.get(position).getTitle());
        tvDetails.setArguments(bundle);
        transaction.replace(R.id.frame_container, tvDetails);
    }
    // add the current transaction to the back stack:
    transaction.addToBackStack("castDetails");
    transaction.commit();

}

From source file:postApp.ActivitiesView.MenuView.NavigationActivity.java

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

    preferences = this.getSharedPreferences("App", Context.MODE_PRIVATE);

    //set the layout
    setContentView(R.layout.activity_main);
    //initilize the toolbar and then set it and then set title.
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*from   ww  w.  j a  v a 2 s  .c  o m*/
    getSupportActionBar().setTitle("Publish PostIt");
    //initilize the drawer and a toggle which opens and closes the drawer and then add it as a drawerlistener
    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    CreateDrawer();
    drawer.addDrawerListener(toggle);

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setItemIconTintList(null);
    //if its not a saved instancestate we set the iniatial frame as a postit
    if (savedInstanceState == null) {
        FragmentManager manager = getFragmentManager();
        manager.beginTransaction().replace(R.id.content_frame, new PostitView()).commit();
    }

    //saving the originallistnere which is a drawer when we switch to a back button later
    mOriginalListener = toggle.getToolbarNavigationClickListener();
    // check if the DrawerLayout is open or closed after the instance state of the DrawerLayout has been restored.
    toggle.syncState();
    presenter = new NavigationPresenter(this, mOriginalListener);
    //checks if a qrcode is stored in the android sharedpreferences
    if (preferences.contains("Qrcode")) {
        String name = preferences.getString("Qrcode", "No mirror is chosen");
        setMirror(name);
    }
    //if no mirror is chosen we call this method
    if (presenter.getMirror().equals("No mirror chosen")) {
        presenter.notPaired();

    }
    //here we just get the user that logged in from before using a bundle
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        presenter.UpdateSettings(extras.getString("bus"), extras.getString("busid"), extras.getString("news"),
                extras.getString("weather"), extras.getString("user"));
        // /The key argument here must match that used in the other activity
    }

    View header = navigationView.getHeaderView(0);
    //sets the navigation drawer view Usernavdrav text
    TextView usrnamenav = (TextView) header.findViewById(R.id.usernavdraw);
    usrnamenav.setText(presenter.getUser());

    navigationView.setNavigationItemSelectedListener(this);

}