Example usage for android.support.v4.app FragmentManager beginTransaction

List of usage examples for android.support.v4.app FragmentManager beginTransaction

Introduction

In this page you can find the example usage for android.support.v4.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.aegamesi.steamtrade.MainActivity.java

public void browseToFragment(Fragment fragment, boolean addToBackStack) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    if (addToBackStack)
        transaction.addToBackStack(null);
    //else/*  ww  w. j a va 2  s.  com*/
    //   fragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);*/
    transaction.replace(R.id.content_frame, fragment, fragment.getClass().getName()).commit();
    drawerLayout.closeDrawer(GravityCompat.START);
}

From source file:android.support.v17.leanback.app.GuidedStepSupportFragment.java

/**
 * Adds the specified GuidedStepSupportFragment to the fragment stack, replacing any existing
 * GuidedStepSupportFragments in the stack, and configuring the fragment-to-fragment custom
 * transitions.  A backstack entry is added, so the fragment will be dismissed when BACK key
 * is pressed.//w  w  w  .  j a v a  2  s .c  om
 * <li>If current fragment on stack is GuidedStepSupportFragment: assign {@link #UI_STYLE_REPLACE} and
 * {@link #onAddSharedElementTransition(FragmentTransaction, GuidedStepSupportFragment)} will be called
 * to perform shared element transition between GuidedStepSupportFragments.
 * <li>If current fragment on stack is not GuidedStepSupportFragment: assign {@link #UI_STYLE_ENTRANCE}
 * <p>
 * Note: currently fragments added using this method must be created programmatically rather
 * than via XML.
 * @param fragmentManager The FragmentManager to be used in the transaction.
 * @param fragment The GuidedStepSupportFragment to be inserted into the fragment stack.
 * @param id The id of container to add GuidedStepSupportFragment, can be android.R.id.content.
 * @return The ID returned by the call FragmentTransaction.commit.
 */
public static int add(FragmentManager fragmentManager, GuidedStepSupportFragment fragment, int id) {
    GuidedStepSupportFragment current = getCurrentGuidedStepSupportFragment(fragmentManager);
    boolean inGuidedStep = current != null;
    if (IS_FRAMEWORK_FRAGMENT && Build.VERSION.SDK_INT >= 21 && Build.VERSION.SDK_INT < 23 && !inGuidedStep) {
        // workaround b/22631964 for framework fragment
        fragmentManager.beginTransaction().replace(id, new DummyFragment(), TAG_LEAN_BACK_ACTIONS_FRAGMENT)
                .commit();
    }
    FragmentTransaction ft = fragmentManager.beginTransaction();

    fragment.setUiStyle(inGuidedStep ? UI_STYLE_REPLACE : UI_STYLE_ENTRANCE);
    ft.addToBackStack(fragment.generateStackEntryName());
    if (current != null) {
        fragment.onAddSharedElementTransition(ft, current);
    }
    return ft.replace(id, fragment, TAG_LEAN_BACK_ACTIONS_FRAGMENT).commit();
}

From source file:co.codecrunch.musicplayerlite.activities.MusicPlayerBaseActivity.java

public void setFragment(int position) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    switch (position) {
    case 0:/*from   w  w w  .  java  2s  . c  o  m*/
        sharedPreferences.edit().putInt("FRAGMENT", position).apply();
        FragmentAllSongs fragmentallsongs = new FragmentAllSongs();
        fragmentTransaction.replace(R.id.fragment, fragmentallsongs);
        fragmentTransaction.commit();
        toolbar.setTitle("All Songs");
        break;
    case 1:
        sharedPreferences.edit().putInt("FRAGMENT", position).apply();
        FragmentLibrary fragmentlibrary = new FragmentLibrary();
        fragmentTransaction.replace(R.id.fragment, fragmentlibrary);
        fragmentTransaction.commit();
        toolbar.setTitle(getResources().getString(R.string.app_name));
        break;
    case 2:
        sharedPreferences.edit().putInt("FRAGMENT", position).apply();
        FragmentFevorite fragmentfevorite = new FragmentFevorite();
        fragmentTransaction.replace(R.id.fragment, fragmentfevorite);
        fragmentTransaction.commit();
        toolbar.setTitle("Favorite");
        break;

    case 3:
        sharedPreferences.edit().putInt("FRAGMENT", position).apply();
        FragmentSettings fragmentsettings = new FragmentSettings();
        fragmentTransaction.replace(R.id.fragment, fragmentsettings);
        fragmentTransaction.commit();
        toolbar.setTitle("Settings");
        break;

    case 4:
        sharedPreferences.edit().putInt("FRAGMENT", position).apply();
        FragmentEqualizer fragmentequalizer = new FragmentEqualizer();
        fragmentTransaction.replace(R.id.fragment, fragmentequalizer);
        fragmentTransaction.commit();
        toolbar.setTitle("Equilizer");
        break;

    case 5:
        sharedPreferences.edit().putInt("FRAGMENT", position).apply();
        FragmentFeedBack fragmentfeedback = new FragmentFeedBack();
        fragmentTransaction.replace(R.id.fragment, fragmentfeedback);
        fragmentTransaction.commit();
        toolbar.setTitle("Send feedback");
        break;
    }
}

From source file:com.actionbarsherlock.sample.demos.app.LoaderThrottleSupport.java

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

    FragmentManager fm = getSupportFragmentManager();

    // Create the list fragment and add it as our sole content.
    if (fm.findFragmentById(android.R.id.content) == null) {
        ThrottledLoaderListFragment list = new ThrottledLoaderListFragment();
        fm.beginTransaction().add(android.R.id.content, list).commit();
    }/*from   ww  w.  j  a  v a2 s .co  m*/
}

From source file:com.alivenet.dmvtaxi.fragment.FragmentArriveDriver.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (view != null) {

        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null)
            parent.removeView(view);/*w  w w.jav  a 2  s .  c o  m*/

    }
    try {
        view = inflater.inflate(R.layout.fragment_time_estemet, container, false);
    } catch (InflateException e) {
    }
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    mPref = getActivity().getSharedPreferences(MYPREF, Context.MODE_PRIVATE);
    mUserId = mPref.getString("userId", null);

    gps = new GPSTracker(getActivity());
    MyApplication.arrivedrivermarker = true;
    progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMessage("Please wait...");
    progressDialog.setCancelable(false);

    mlinerlayoutbottom = (LinearLayout) view.findViewById(R.id.ll_bottom);
    mphone = (ImageView) view.findViewById(R.id.iv_phone);
    mphonenumber = (TextView) view.findViewById(R.id.tv_phonenumber);
    marrivaltime = (TextView) view.findViewById(R.id.tv_textarrival);
    mname = (TextView) view.findViewById(R.id.tv_name);
    mlicence = (TextView) view.findViewById(R.id.tv_licence);
    mtaximodel = (TextView) view.findViewById(R.id.tv_model);
    muserImage = (ImageView) view.findViewById(R.id.imageView_close);
    getLatLong();
    btnSplite = (Button) view.findViewById(R.id.btn_splite_rides);

    btnSplite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent in = new Intent(getActivity(), SplitAddFrnd.class);
            startActivity(in);
        }
    });

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

            String uri = "tel:" + mphonenumber.getText().toString().trim();
            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse(uri));
            startActivity(intent);
        }
    });

    System.out.println("userId>>>>>>>>>>>>>>>>>>>>>" + mUserId);

    mname.setText(MyApplication.driverName);
    mlicence.setText(MyApplication.licenseId);
    mtaximodel.setText(MyApplication.vehicle);
    mphonenumber.setText(MyApplication.mobileNO);

    Picasso.with(getActivity()).load(MyApplication.imageUrl).error(R.mipmap.avtar).placeholder(R.mipmap.avtar)
            .into(muserImage);

    System.out.println("driverImageurl" + "chceck=" + MyApplication.imageUrl);

    mphonenumber.setText("Call To" + " " + MyApplication.driverName);

    final SinchClient sinchClient = Sinch.getSinchClientBuilder().context(getActivity()).userId(mUserId)
            .applicationKey("3b013f09-db1f-422e-ac7b-c6498e119612")
            .applicationSecret("LMhelEFYtUqms55VX1C7MQ==").environmentHost("sandbox.sinch.com").build();

    sinchClient.setSupportCalling(true);
    sinchClient.start();
    mphone.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (call == null) {
                if (MyApplication.mobileNO != null && !MyApplication.mobileNO.equals("")) {
                    call = sinchClient.getCallClient().callPhoneNumber("+" + MyApplication.mobileNO);
                    System.out.println("mobile_number" + MyApplication.mobileNO);
                    //call = sinchClient.getCallClient().callPhoneNumber("+918510834641");
                    try {
                        call.addCallListener(new SinchCallListener());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mphonenumber.setText("Hang Up");
                }
            } else {
                call.hangup();
            }
        }
    });

    view.setFocusableInTouchMode(true);
    view.requestFocus();
    view.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                // handle back button's click listener

                if (keyCode == KeyEvent.KEYCODE_BACK) {

                    Fragment homeFragment = new FragmentMainScreen();
                    FragmentManager frgManager;
                    frgManager = getFragmentManager();
                    frgManager.beginTransaction().replace(R.id.fragment_switch, homeFragment).commit();

                    return true;
                }

                return true;
            }
            return false;
        }
    });

    return view;
}

From source file:com.christophergs.mbientbasic.NavigationActivity.java

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    Log.i(TAG, String.format("Fragment ID: %d", id));

    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    if (currentFragment != null) {
        transaction.detach(currentFragment);
    }//from   w  ww  . j a  va 2s.c  o  m

    if (currentFragment2 != null) {
        transaction.detach(currentFragment2);
    }

    //we keep tag 1 as the per the mbient code and make tag 2 the adjusted gyro,
    //knowing that the BothFragment is a copy of accelerometer with stream adjustments
    String fragmentTag = FRAGMENT_CLASSES.get(id).getCanonicalName();
    String fragmentTag2 = FRAGMENT_CLASSES.get(2131624130).getCanonicalName(); //Gyro New
    //2131165353

    Log.i(TAG, String.format("Fragment Tag: %s", fragmentTag));

    if (FRAGMENT_CLASSES.get(id).getCanonicalName().equals("com.christophergs.mbientbasic.BothFragment")) {
        Log.i(TAG, String.format("Both fragment selected2: %s", fragmentTag));
        currentFragment = fragmentManager.findFragmentByTag(fragmentTag);
        currentFragment2 = fragmentManager.findFragmentByTag("com.christophergs.mbientbasic.GyroFragmentNew");
    } else {
        currentFragment = fragmentManager.findFragmentByTag(fragmentTag);
        Log.i(TAG, String.format("Did not find tag: %s", fragmentTag));
    }

    if (currentFragment == null) {
        try {
            currentFragment = FRAGMENT_CLASSES.get(id).getConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Cannot instantiate fragment", e);
        }

        transaction.add(R.id.container, currentFragment, fragmentTag);
    }

    if (FRAGMENT_CLASSES.get(id).getCanonicalName().equals("com.christophergs.mbientbasic.BothFragment")) {

        if (currentFragment2 == null) {
            try {
                currentFragment2 = FRAGMENT_CLASSES.get(2131624130).getConstructor().newInstance();//new gyro
            } catch (Exception e) {
                throw new RuntimeException("Cannot instantiate fragment", e);
            }

            transaction.add(R.id.container2, currentFragment2, fragmentTag2);
        }
    }

    if (FRAGMENT_CLASSES.get(id).getCanonicalName().equals("com.christophergs.mbientbasic.BothFragment")) {
        transaction.attach(currentFragment);
        transaction.attach(currentFragment2);
        transaction.commit();
    } else {
        transaction.attach(currentFragment);
        transaction.commit();
    }

    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(item.getTitle());
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);

    return true;
}

From source file:at.fhooe.mcm.saap.facebook.HelloFacebookSampleActivity.java

private void showPickerFragment(PickerFragment<?> fragment) {
    fragment.setOnErrorListener(new PickerFragment.OnErrorListener() {
        @Override/*from w  ww . j  a  v  a 2s.  co  m*/
        public void onError(PickerFragment<?> pickerFragment, FacebookException error) {
            String text = getString(R.string.exception, error.getMessage());
            Toast toast = Toast.makeText(HelloFacebookSampleActivity.this, text, Toast.LENGTH_SHORT);
            toast.show();
        }
    });

    FragmentManager fm = getSupportFragmentManager();
    fm.beginTransaction().replace(R.id.fragment_container, fragment).addToBackStack(null).commit();

    controlsContainer.setVisibility(View.GONE);

    // We want the fragment fully created so we can use it immediately.
    fm.executePendingTransactions();

    fragment.loadData(true);
}

From source file:com.adamkruger.myipaddressinfo.MainActivity.java

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

    FragmentManager fragmentManager = getSupportFragmentManager();
    mIPAddressInfoFragment = (IPAddressInfoFragment) fragmentManager
            .findFragmentByTag(TAG_IP_ADDRESS_INFO_FRAGMENT);
    mAdditionalInfoPager = (ViewPager) findViewById(R.id.other_info_container);
    mAdditionalInfoPageIndicator = (CirclePageIndicator) findViewById(R.id.other_info_indicator);

    if (mIPAddressInfoFragment == null) {
        mIPAddressInfoFragment = new IPAddressInfoFragment();
        fragmentManager.beginTransaction()
                .add(R.id.ip_address_info_container, mIPAddressInfoFragment, TAG_IP_ADDRESS_INFO_FRAGMENT)
                .commit();//from w  w w . j  ava2s .  c  om
    }

    // NOTE that this hack assumes the fragment positions in the ViewPager
    // corresponding to the FragmentPagerAdapter's SetPages call below
    mNetworkInfoFragment = (NetworkInfoFragment) fragmentManager
            .findFragmentByTag("android:switcher:" + R.id.other_info_container + ":" + 0);
    mProxySettingsFragment = (ProxySettingsFragment) fragmentManager
            .findFragmentByTag("android:switcher:" + R.id.other_info_container + ":" + 1);
    mGeoIPProviderSettingsFragment = (GeoIPProviderSettingsFragment) fragmentManager
            .findFragmentByTag("android:switcher:" + R.id.other_info_container + ":" + 2);

    if (mNetworkInfoFragment == null) {
        mNetworkInfoFragment = new NetworkInfoFragment();
    }

    if (mProxySettingsFragment == null) {
        mProxySettingsFragment = new ProxySettingsFragment();
    }

    if (mGeoIPProviderSettingsFragment == null) {
        mGeoIPProviderSettingsFragment = new GeoIPProviderSettingsFragment();
    }

    mAdditionalInfoPagerAdapter = new AdditionalInfoFragmentPagerAdapter(fragmentManager);
    mAdditionalInfoPagerAdapter.SetPages(
            new Fragment[] { mNetworkInfoFragment, mProxySettingsFragment, mGeoIPProviderSettingsFragment });
    mAdditionalInfoPager.setAdapter(mAdditionalInfoPagerAdapter);
    mAdditionalInfoPageIndicator.setViewPager(mAdditionalInfoPager);
    mAdditionalInfoPageIndicator.setOnPageChangeListener(new AdditionalInfoPageChangeListener(this));

    int additionalInfoCurrentPage = PreferenceManager.getDefaultSharedPreferences(this)
            .getInt(getResources().getString(R.string.PREFERENCE_ADDITIONAL_INFO_PAGE), 0);
    mAdditionalInfoPager.setCurrentItem(additionalInfoCurrentPage);

    findViewById(R.id.ip_address_info_container).getViewTreeObserver()
            .addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    // Compute the best panel height so that as much as
                    // possible of both the IPAddressInfoFragment and the
                    // SlidingUpPanelLayout is showing, without wasting
                    // empty space
                    SlidingUpPanelLayout slidingPanelLayout = (SlidingUpPanelLayout) findViewById(
                            R.id.sliding_panel_layout);
                    if (slidingPanelLayout != null) {
                        int ipAddressFragmentHeight = mIPAddressInfoFragment.getOptimalHeight();
                        // TODO: dimen
                        int minimumPanelHeight = (int) (60 * getResources().getDisplayMetrics().density + 0.5f);

                        int optimalSlidingPanelHeight = slidingPanelLayout.getBottom()
                                - ipAddressFragmentHeight;
                        if (optimalSlidingPanelHeight > minimumPanelHeight) {
                            slidingPanelLayout.setPanelHeight(optimalSlidingPanelHeight);
                            // Sometimes changing the sliding panel height
                            // leaves a shadow artifact.
                            // This forces the IP Address fragment to
                            // redraw.
                            mIPAddressInfoFragment.getView().invalidate();
                        }
                    }
                }
            });
}

From source file:com.barak.pix.NewPostActivity.java

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

    // find the retained fragment on activity restarts
    FragmentManager fm = getSupportFragmentManager();
    mTaskFragment = (NewPostUploadTaskFragment) fm.findFragmentByTag(TAG_TASK_FRAGMENT);

    // create the fragment and data the first time
    if (mTaskFragment == null) {
        // add the fragment
        mTaskFragment = new NewPostUploadTaskFragment();
        fm.beginTransaction().add(mTaskFragment, TAG_TASK_FRAGMENT).commit();
    }//from   w ww  . ja  va2s .c  o m

    mImageView = (ImageView) findViewById(R.id.new_post_picture);

    mImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showImagePicker();
        }
    });
    Bitmap selectedBitmap = mTaskFragment.getSelectedBitmap();
    Bitmap thumbnail = mTaskFragment.getThumbnail();
    if (selectedBitmap != null) {
        mImageView.setImageBitmap(selectedBitmap);
        mResizedBitmap = selectedBitmap;
    }
    if (thumbnail != null) {
        mThumbnail = thumbnail;
    }
    final EditText descriptionText = (EditText) findViewById(R.id.new_post_text);

    mSubmitButton = (Button) findViewById(R.id.new_post_submit);
    mSubmitButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (mResizedBitmap == null) {
                Toast.makeText(NewPostActivity.this, "    !!!",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            if (mLocation == null) {
                Toast.makeText(NewPostActivity.this, " ? ?", Toast.LENGTH_SHORT)
                        .show();
                return;
            }
            String postText = descriptionText.getText().toString();
            if (TextUtils.isEmpty(postText)) {
                descriptionText.setError(getString(R.string.error_required_field));
                return;
            }
            showProgressDialog(getString(R.string.post_upload_progress_message));
            mSubmitButton.setEnabled(false);

            Long timestamp = System.currentTimeMillis();

            String bitmapPath = "https://pictures-e88fc.firebaseio.com" + "/" + FirebaseUtil.getCurrentUserId()
                    + "/full/" + timestamp.toString() + "/";
            String thumbnailPath = "https://pictures-e88fc.firebaseio.com" + "/"
                    + FirebaseUtil.getCurrentUserId() + "/thumb/" + timestamp.toString() + "/";
            mTaskFragment.uploadPost(mResizedBitmap, bitmapPath, mThumbnail, thumbnailPath,
                    mFileUri.getLastPathSegment(), postText, mLocation.getLatitude(), mLocation.getLongitude());
        }
    });
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationListener = new MyLocationListener();
    if (checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION, getApplicationContext(),
            NewPostActivity.this)) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
    } else {
        requestPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION, 11, getApplicationContext(),
                this);
    }
}

From source file:com.dgsd.android.ShiftTracker.EditShiftActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_with_single_fragment);

    setupActionBar();//  w ww. jav  a  2 s  . c  om

    FragmentManager fm = getSupportFragmentManager();
    if (savedInstanceState != null)
        mEditShiftFragment = (EditShiftFragment) fm.getFragment(savedInstanceState, KEY_FRAGMENT);

    if (mEditShiftFragment == null) {
        final Shift shift = (Shift) getIntent().getParcelableExtra(EXTRA_SHIFT);
        final int jd = getIntent().getIntExtra(EXTRA_JULIAN_DAY, -1);

        if (shift != null)
            mEditShiftFragment = EditShiftFragment.newInstance(shift);
        else
            mEditShiftFragment = EditShiftFragment.newInstance(jd);

        fm.beginTransaction().replace(R.id.container, mEditShiftFragment).commit();
    }
}