Example usage for android.app FragmentTransaction remove

List of usage examples for android.app FragmentTransaction remove

Introduction

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

Prototype

public abstract FragmentTransaction remove(Fragment fragment);

Source Link

Document

Remove an existing fragment.

Usage

From source file:net.hockeyapp.android.internal.CheckUpdateTask.java

private void showUpdateFragment(final JSONArray updateInfo) {
    FragmentTransaction fragmentTransaction = activity.getFragmentManager().beginTransaction();
    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

    Fragment existingFragment = activity.getFragmentManager().findFragmentByTag("hockey_update_dialog");
    if (existingFragment != null) {
        fragmentTransaction.remove(existingFragment);
    }//w  ww. jav  a  2 s. c  om
    fragmentTransaction.addToBackStack(null);

    // Create and show the dialog
    Class<? extends UpdateFragment> fragmentClass = UpdateFragment.class;
    if (listener != null) {
        fragmentClass = listener.getUpdateFragmentClass();
    }

    try {
        Method method = fragmentClass.getMethod("newInstance", JSONArray.class, String.class);
        DialogFragment updateFragment = (DialogFragment) method.invoke(null, updateInfo, getURLString("apk"));
        updateFragment.show(fragmentTransaction, "hockey_update_dialog");
    } catch (Exception e) {
        Log.d(Constants.TAG, "An exception happened while showing the update fragment:");
        e.printStackTrace();
        Log.d(Constants.TAG, "Showing update activity instead.");
        startUpdateIntent(updateInfo, false);
    }
}

From source file:com.esri.android.mapsapp.MapsAppActivity.java

/**
 * Opens the map represented by the specified portal item or if null, opens
 * a default map.//from  w w w .  j a v  a2 s . co m
 */
public void showMap(String portalItemId, String basemapPortalItemId) {

    // remove existing MapFragment explicitly, simply replacing it can cause
    // the app to freeze when switching basemaps
    FragmentTransaction transaction;
    FragmentManager fragmentManager = getFragmentManager();
    Fragment currentMapFragment = fragmentManager.findFragmentByTag(MapFragment.TAG);
    if (currentMapFragment != null) {
        transaction = fragmentManager.beginTransaction();
        transaction.remove(currentMapFragment);
        transaction.commit();
    }

    MapFragment mapFragment = MapFragment.newInstance(portalItemId, basemapPortalItemId);

    transaction = fragmentManager.beginTransaction();
    transaction.replace(R.id.maps_app_activity_content_frame, mapFragment, MapFragment.TAG);
    transaction.addToBackStack(null);
    transaction.commit();

    invalidateOptionsMenu(); // reload the options menu
}

From source file:net.sf.sprockets.app.ui.PanesActivity.java

/**
 * Use your own layout for the panes.//w  w w. j  a  va  2 s.c  o  m
 *
 * @param pagerId {@code R.id} value for the ViewPager in the single pane layout
 * @param pane1Id {@code R.id} value for the first pane in the multi-pane layout
 * @param pane2Id {@code R.id} value for the second pane in the multi-pane layout
 */
public void setContentView(int layoutResId, int pagerId, int pane1Id, int pane2Id) {
    setContentView(layoutResId);
    Fragment pane1 = findFragmentByPane(1);
    Fragment pane2 = findFragmentByPane(2);
    ViewPager pager = findById(this, pagerId);
    /* do we need to move the fragments between the single and multi-pane layouts? */
    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = null;
    if (pane2 == null) {
        pane2 = getFragment(2);
    } else if (pane2.getId() != (pager != null ? pagerId : pane2Id)) {
        ft = fm.beginTransaction().remove(pane2); // remove in reverse to preserve indices
    }
    if (pane1 == null) {
        pane1 = getFragment(1);
    } else if (pane1.getId() != (pager != null ? pagerId : pane1Id)) {
        if (ft == null) {
            ft = fm.beginTransaction();
        }
        ft.remove(pane1);
    }
    if (ft != null) {
        ft.commitAllowingStateLoss();
        fm.executePendingTransactions(); // force removes so can add to a different container
    }
    /* add the fragments to the panes */
    if (pager != null) {
        pager.setAdapter(new PanesAdapter(pane1, pane2));
    } else {
        ft = null;
        if (pane1.getId() != pane1Id) {
            ft = Fragments.open(this).add(pane1Id, pane1, PANE_1);
        }
        if (pane2.getId() != pane2Id) {
            if (ft == null) {
                ft = Fragments.open(this);
            }
            ft.add(pane2Id, pane2, PANE_2);
        }
        if (ft != null) {
            ft.commitAllowingStateLoss();
        }
    }
}

From source file:ab.util.AbDialogUtil.java

/**
 * ??Fragment./*from w w w.  j av a  2s .  c  om*/
 * 
 * @param context
 *            the context
 */
public static void removeDialog(Context context) {
    try {
        FragmentActivity activity = (FragmentActivity) context;
        FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
        Fragment prev = activity.getFragmentManager().findFragmentByTag(mDialogTag);
        if (prev != null) {
            ft.remove(prev);
        }
        ft.addToBackStack(null);
        if (context != null) {
            ft.commit();
        }
    } catch (Exception e) {
        // ?Activity??
        e.printStackTrace();
    }
}

From source file:io.coldstart.android.TrapListActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.GCMStatus: {
        subscribeToMessages();//from w  w w.jav a  2s .c  o  m
        return true;
    }

    case R.id.ChangeKey: {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
        editor.putBoolean("firstRun", true);
        editor.putString("APIKey", "");
        editor.putString("keyPassword", "");
        editor.commit();
        Intent intent = getIntent();
        overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        finish();
        overridePendingTransition(0, 0);
        startActivity(intent);
        return true;
    }

    case R.id.PauseAlerts: {
        new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle("Delete Traps for selected host?")
                .setMessage(
                        "Are you sure you want to logout?\nYou'll no longer receive any alerts, they won't be cached on the server and the app will close.")
                .setPositiveButton("Yes, Logout", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.i("onOptionsItemSelected", "Logging Out");
                        (new Thread() {
                            public void run() {
                                API api = new API();

                                try {
                                    if (api.logoutGCMAccount(settings.getString("APIKey", ""),
                                            settings.getString("keyPassword", ""), securityID)) {
                                        //We successfully logged out
                                        runOnUiThread(new Runnable() {
                                            public void run() {
                                                gcmStatus.setIcon(R.drawable.ic_action_gcm_failed);
                                                Toast.makeText(getApplicationContext(),
                                                        "Succesfully logged out. Tap the GCM icon or relaunch app to login again",
                                                        Toast.LENGTH_SHORT).show();
                                            }
                                        });
                                    } else {
                                        //TODO Popup to the user that there was a problem logging out
                                        runOnUiThread(new Runnable() {
                                            public void run() {
                                                gcmStatus.setIcon(R.drawable.ic_action_gcm_failed);
                                                Toast.makeText(getApplicationContext(),
                                                        "There was a problem logging out.", Toast.LENGTH_SHORT)
                                                        .show();
                                            }
                                        });
                                    }

                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            TrapListActivity.this.invalidateOptionsMenu();
                                        }
                                    });
                                } catch (Exception e) {
                                    //TODO this is probably pretty bad!
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    }
                }).setNegativeButton("No", null).show();
        return true;
    }

    case R.id.Settings: {
        Intent SettingsIntent = new Intent(TrapListActivity.this, SettingsFragment.class);
        this.startActivityForResult(SettingsIntent, DISPLAY_SETTINGS);
        return true;
    }

    case R.id.SeeAPIKey: {
        if (dialogFragment != null)
            dialogFragment.dismiss();

        FragmentTransaction ft = getFragmentManager().beginTransaction();
        Fragment prev = getFragmentManager().findFragmentByTag("dialog");
        if (prev != null) {
            ft.remove(prev);
            Log.i("prev", "Removing");
        }
        ft.addToBackStack(null);

        // Create and show the dialog.
        dialogFragment = ViewAPIKeyDialog.newInstance(settings.getString("APIKey", ""));
        dialogFragment.setCancelable(true);
        dialogFragment.show(ft, "dialog");

        return true;
    }

    /*case R.id.Filters:
    {
        if(dialogFragment != null)
            dialogFragment.dismiss();
            
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        Fragment prev = getFragmentManager().findFragmentByTag("dialog");
        if (prev != null)
        {
            ft.remove(prev);
            Log.i("prev","Removing");
        }
        ft.addToBackStack(null);
            
        // Create and show the dialog.
        dialogFragment = HostFilterDialog.newInstance();
        dialogFragment.setCancelable(true);
        dialogFragment.show(ft, "dialog");
            
        return true;
    }*/
    }

    return false;
}

From source file:com.android.purenexussettings.TinkerActivity.java

private void removeCurrent() {
    // update the main content by replacing fragments, first by removing the old
    FragmentTransaction fragtrans = fragmentManager.beginTransaction();
    fragtrans.setCustomAnimations(R.anim.fadein, R.anim.fadeout, R.anim.fadein, R.anim.fadeout);
    fragtrans.remove(fragmentManager.findFragmentById(R.id.frame_container));
    fragtrans.commit();/*from ww  w .  j a  va 2  s .  com*/
}

From source file:com.notalenthack.blaster.CommandActivity.java

private void launchCommand(Command cmd) {

    FragmentTransaction ft = getFragmentManager().beginTransaction();
    Fragment prev = getFragmentManager().findFragmentByTag(LaunchCommandDialog.TAG_LAUNCH_DIALOG);
    if (prev != null) {
        ft.remove(prev);
    }/*from w w w .  j a v a  2  s .co  m*/
    ft.addToBackStack(null);

    // Create and show the dialog.
    DialogFragment newFragment = LaunchCommandDialog.newInstance(cmd, this);
    newFragment.show(ft, LaunchCommandDialog.TAG_LAUNCH_DIALOG);
}

From source file:com.notalenthack.blaster.CommandActivity.java

private void editCommand(Command command) {

    FragmentTransaction ft = getFragmentManager().beginTransaction();
    Fragment prev = getFragmentManager().findFragmentByTag(EditCommandDialog.TAG_EDIT_COMMAND_DIALOG);
    if (prev != null) {
        ft.remove(prev);
    }//from w w  w . jav  a 2  s .c o  m
    ft.addToBackStack(null);

    // Create and show the dialog.
    DialogFragment newFragment = EditCommandDialog.newInstance(command, this);
    newFragment.show(ft, EditCommandDialog.TAG_EDIT_COMMAND_DIALOG);
}

From source file:org.opendatakit.services.preferences.fragments.ServerSettingsFragment.java

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

    PropertiesSingleton props = ((IOdkAppPropertiesActivity) this.getActivity()).getProps();

    addPreferencesFromResource(R.xml.server_preferences);

    // not super safe, but we're just putting in this mode to help
    // administrate
    // would require code to access it
    boolean adminMode;
    adminMode = (this.getArguments() == null) ? false
            : (this.getArguments().containsKey(IntentConsts.INTENT_KEY_SETTINGS_IN_ADMIN_MODE)
                    ? this.getArguments().getBoolean(IntentConsts.INTENT_KEY_SETTINGS_IN_ADMIN_MODE)
                    : false);/*ww w .j a v  a 2 s  . c o m*/

    String adminPwd = props.getProperty(CommonToolProperties.KEY_ADMIN_PW);
    boolean adminConfigured = (adminPwd != null && adminPwd.length() != 0);

    boolean serverAvailable = !adminConfigured
            || props.getBooleanProperty(CommonToolProperties.KEY_CHANGE_SYNC_SERVER);

    PreferenceCategory serverCategory = (PreferenceCategory) findPreference(
            CommonToolProperties.GROUPING_SERVER_CATEGORY);

    // Initialize the Server URL Text Preference
    mServerUrlPreference = (EditTextPreference) findPreference(CommonToolProperties.KEY_SYNC_SERVER_URL);
    if (props.containsKey(CommonToolProperties.KEY_SYNC_SERVER_URL)) {
        String url = props.getProperty(CommonToolProperties.KEY_SYNC_SERVER_URL);
        mServerUrlPreference.setSummary(url);
        mServerUrlPreference.setText(url);
    }

    mServerUrlPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            String url = newValue.toString();

            // disallow any whitespace
            if (url.contains(" ") || !url.equals(url.trim())) {
                Toast.makeText(getActivity().getApplicationContext(), R.string.url_error_whitespace,
                        Toast.LENGTH_SHORT).show();
                return false;
            }

            // remove all trailing "/"s
            while (url.endsWith("/")) {
                url = url.substring(0, url.length() - 1);
            }

            boolean isValid = false;
            try {
                new URL(url);
                isValid = true;
            } catch (MalformedURLException e) {
                // ignore
            }

            if (isValid) {
                preference.setSummary(newValue.toString());

                PropertiesSingleton props = ((IOdkAppPropertiesActivity) ServerSettingsFragment.this
                        .getActivity()).getProps();
                props.setProperty(CommonToolProperties.KEY_SYNC_SERVER_URL, newValue.toString());
                props.setProperty(CommonToolProperties.KEY_ROLES_LIST, "");
                props.setProperty(CommonToolProperties.KEY_USERS_LIST, "");
                return true;
            } else {
                Toast.makeText(getActivity().getApplicationContext(), R.string.url_error, Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
        }
    });
    mServerUrlPreference.setSummary(mServerUrlPreference.getText());
    mServerUrlPreference.getEditText().setFilters(new InputFilter[] { getReturnFilter() });

    mServerUrlPreference.setEnabled(serverAvailable || adminMode);

    boolean credentialAvailable = !adminConfigured
            || props.getBooleanProperty(CommonToolProperties.KEY_CHANGE_AUTHENTICATION_TYPE);
    mSignOnCredentialPreference = (ListPreference) findPreference(CommonToolProperties.KEY_AUTHENTICATION_TYPE);
    if (props.containsKey(CommonToolProperties.KEY_AUTHENTICATION_TYPE)) {
        String chosenFontSize = props.getProperty(CommonToolProperties.KEY_AUTHENTICATION_TYPE);
        CharSequence entryValues[] = mSignOnCredentialPreference.getEntryValues();
        for (int i = 0; i < entryValues.length; i++) {
            String entry = entryValues[i].toString();
            if (entry.equals(chosenFontSize)) {
                mSignOnCredentialPreference.setValue(entry);
                mSignOnCredentialPreference.setSummary(mSignOnCredentialPreference.getEntries()[i]);
            }
        }
    }

    mSignOnCredentialPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            int index = ((ListPreference) preference).findIndexOfValue(newValue.toString());
            String entry = (String) ((ListPreference) preference).getEntries()[index];
            ((ListPreference) preference).setSummary(entry);

            PropertiesSingleton props = ((IOdkAppPropertiesActivity) ServerSettingsFragment.this.getActivity())
                    .getProps();
            props.setProperty(CommonToolProperties.KEY_AUTHENTICATION_TYPE, newValue.toString());
            props.setProperty(CommonToolProperties.KEY_ROLES_LIST, "");
            props.setProperty(CommonToolProperties.KEY_USERS_LIST, "");
            return true;
        }
    });

    mSignOnCredentialPreference.setEnabled(credentialAvailable || adminMode);

    //////////////////
    mUsernamePreference = (EditTextPreference) findPreference(CommonToolProperties.KEY_USERNAME);
    if (props.containsKey(CommonToolProperties.KEY_USERNAME)) {
        String user = props.getProperty(CommonToolProperties.KEY_USERNAME);
        mUsernamePreference.setSummary(user);
        mUsernamePreference.setText(user);
    }

    mUsernamePreference.setOnPreferenceChangeListener(this);

    mUsernamePreference.getEditText().setFilters(new InputFilter[] { getReturnFilter() });

    boolean usernamePasswordAvailable = !adminConfigured
            || props.getBooleanProperty(CommonToolProperties.KEY_CHANGE_USERNAME_PASSWORD);

    mUsernamePreference.setEnabled(usernamePasswordAvailable || adminMode);

    PasswordPreferenceScreen passwordScreen = (PasswordPreferenceScreen) this
            .findPreference(CommonToolProperties.GROUPING_PASSWORD_SCREEN);
    passwordScreen.setCallback(new PasswordPreferenceScreen.PasswordActionCallback() {
        @Override
        public void showPasswordDialog() {
            // DialogFragment.show() will take care of adding the fragment
            // in a transaction.  We also want to remove any currently showing
            // dialog, so make our own transaction and take care of that here.
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            Fragment prev = getFragmentManager()
                    .findFragmentByTag(CommonToolProperties.GROUPING_PASSWORD_SCREEN);
            if (prev != null) {
                ft.remove(prev);
            }

            // Create and show the dialog.
            PasswordDialogFragment newFragment = PasswordDialogFragment
                    .newPasswordDialog(CommonToolProperties.KEY_PASSWORD);
            newFragment.show(ft, CommonToolProperties.GROUPING_PASSWORD_SCREEN);
        }
    });

    passwordScreen.setEnabled((usernamePasswordAvailable || adminMode));

    mSelectedGoogleAccountPreference = (ListPreference) findPreference(CommonToolProperties.KEY_ACCOUNT);

    // get list of google accounts
    final Account[] accounts = AccountManager.get(getActivity().getApplicationContext())
            .getAccountsByType("com.google");
    ArrayList<String> accountEntries = new ArrayList<String>();
    ArrayList<String> accountValues = new ArrayList<String>();

    for (int i = 0; i < accounts.length; i++) {
        accountEntries.add(accounts[i].name);
        accountValues.add(accounts[i].name);
    }
    accountEntries.add(getString(R.string.no_account));
    accountValues.add("");

    mSelectedGoogleAccountPreference.setEntries(accountEntries.toArray(new String[accountEntries.size()]));
    mSelectedGoogleAccountPreference.setEntryValues(accountValues.toArray(new String[accountValues.size()]));
    mSelectedGoogleAccountPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            int index = ((ListPreference) preference).findIndexOfValue(newValue.toString());
            String value = (String) ((ListPreference) preference).getEntryValues()[index];
            preference.setSummary(value);
            PropertiesSingleton props = ((IOdkAppPropertiesActivity) ServerSettingsFragment.this.getActivity())
                    .getProps();
            props.setProperty(CommonToolProperties.KEY_ACCOUNT, value);
            props.setProperty(CommonToolProperties.KEY_AUTH, "");
            props.setProperty(CommonToolProperties.KEY_ROLES_LIST, "");
            props.setProperty(CommonToolProperties.KEY_USERS_LIST, "");
            return true;
        }
    });

    String googleAccount = props.getProperty(CommonToolProperties.KEY_ACCOUNT);
    if (googleAccount == null) {
        googleAccount = "";
    }
    boolean found = false;
    for (int i = 0; i < accountValues.size(); ++i) {
        if (googleAccount.equals(accountValues.get(i))) {
            mSelectedGoogleAccountPreference.setValue(googleAccount);
            mSelectedGoogleAccountPreference.setSummary(accountEntries.get(i));
            found = true;
        }
    }
    if (!found) {
        // clear the property (prevents clarice@ from being identified)
        props.setProperty(CommonToolProperties.KEY_ACCOUNT, "");
        // set to "none"
        mSelectedGoogleAccountPreference.setValue(accountValues.get(accountValues.size() - 1));
        mSelectedGoogleAccountPreference.setSummary(accountEntries.get(accountEntries.size() - 1));
    }

    Boolean googleAccountAvailable = props.getBooleanProperty(CommonToolProperties.KEY_CHANGE_GOOGLE_ACCOUNT);
    mSelectedGoogleAccountPreference.setEnabled(googleAccountAvailable || adminMode);

    if (!adminMode && (!serverAvailable || !credentialAvailable || !usernamePasswordAvailable
            || !googleAccountAvailable)) {
        serverCategory.setTitle(R.string.server_restrictions_apply);
    }

    mOfficeId = (EditTextPreference) findPreference("common.officeID");
    this.settingsUtils = new SettingsUtils(getActivity().getApplicationContext());
    String officeId = settingsUtils.getOfficeIdFromFile();
    if (officeId != null && !officeId.equals("null")) {
        mOfficeId.setSummary(officeId);
        mOfficeId.setText(officeId);
    }

    mOfficeId.setOnPreferenceChangeListener(this);
}

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

public void removePanelWithoutClosing(SplitPanel p) {
    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
    fragmentTransaction.remove(p);
    fragmentTransaction.commit();//from  w  w  w .  java2s.c o  m

    panelCount--;
}