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:br.com.android.cotuca.toptask.Activitys.MSimplesActivity.java

private void selectItem(int posicao) {

    FragmentManager fm = getFragmentManager();

    if (posicao == 0) {
        Fragment f_tarefas = new FragmentTarefas();
        if (idProjetoSelecionado != 0) {
            Bundle dadosProjeto = new Bundle();
            dadosProjeto.putInt(ContratoProjetos.Colunas._ID, idProjetoSelecionado);

            f_tarefas.setArguments(dadosProjeto);
        }/*w  w  w.j  ava2  s.  c  om*/
        fm.beginTransaction().replace(R.id.content_frame, f_tarefas).commit();

    } else if (posicao == 1) {

        if (!dao.getTarefasDoUsuarioNoProjetos(idProjetoSelecionado, idUsuarioSelecionado).isEmpty()) {

            Intent i = new Intent(this, GraficosActivity.class);
            Bundle dados = new Bundle();
            dados.putInt(Tags.ID_PROJETO, idProjetoSelecionado);
            dados.putInt(Tags.ID_USUARIO, idUsuarioSelecionado);
            i.putExtras(dados);
            startActivity(i);
        } else {
            Log.i("lista de tarefas vazia", "lista de tarefas vazia");
            Toast.makeText(getApplicationContext(), "Voce ainda nao possui tarefas", Toast.LENGTH_SHORT).show();
        }
    } else if (posicao == 2) {
        Intent iSairProjetoAtual = new Intent(this, ProjetosActivity.class);
        Bundle dados = new Bundle();
        dados.putInt(Tags.ID_USUARIO, idUsuarioSelecionado);
        iSairProjetoAtual.putExtras(dados);
        iSairProjetoAtual.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(iSairProjetoAtual);
    }
    mDrawerList.setItemChecked(posicao, true);
    setTitle(mPaginaTitulo[posicao]);
    mDrawerLayout.closeDrawer(mDrawerList);
}

From source file:hu.zelena.guide.MainActivity.java

@Override
public void onBackPressed() {
    if (mDrawer.isDrawerOpen(GravityCompat.START)) {
        mDrawer.closeDrawers();//from w w  w. j a v a2s.  co  m
    } else {

        if (doubleBackToExitPressedOnce) {
            super.onBackPressed();
            return;
        }

        Fragment fragment = new AboutFragment();
        if (fragment != null) {
            firstFrag = true;
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
            setTitle("MOBILTUDS GUIDE");

            final Menu menu = nvDrawer.getMenu();
            for (int i = 0; i < menu.size(); i++) {
                MenuItem item = menu.getItem(i);
                if (item.hasSubMenu()) {
                    SubMenu subMenu = item.getSubMenu();
                    for (int j = 0; j < subMenu.size(); j++) {
                        MenuItem subMenuItem = subMenu.getItem(j);
                        subMenuItem.setChecked(false);
                    }
                } else {
                    item.setChecked(false);
                }
            }
        } else {
            Intent i = new Intent(this, ErrorActivity.class);
            i.putExtra("error", "Nem sikerlt a HOME-FRAGMENT betltse. [Null object]");
            startActivity(i);

            Log.e("MainActivity", "Error in creating fragment");
        }
        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(this, "Nyomja meg mgegyszer a kilpshez", Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;
            }
        }, 2000);
    }
}

From source file:tools.ToolsManpowerHomeActivity.java

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

    Fragment fragment;//from ww w  .  j a  va  2 s  .  com
    Bundle bundle;

    FragmentManager fragmentManager;
    switch (position) {

    case 0:

        fragment = new ToolsManpowerHomeFragmet();
        bundle = new Bundle();
        // bundle.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
        fragment.setArguments(bundle);

        fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

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

        break;

    case 1:

        fragment = new UpdateManpowerFragmet();
        bundle = new Bundle();
        // bundle.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
        fragment.setArguments(bundle);

        fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

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

        break;

    case 2:

        fragment = new ToolUpdateFragmet();
        bundle = new Bundle();
        // bundle.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
        fragment.setArguments(bundle);

        fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

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

        break;

    case 3:

        AlertDialog.Builder bulder = new AlertDialog.Builder(ToolsManpowerHomeActivity.this);
        bulder.setTitle("Are you sure ?....");
        bulder.setIcon(R.drawable.ic_launcher);
        bulder.setMessage("You want to Logout");
        bulder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(ToolsManpowerHomeActivity.this, MainActivity.class);
                startActivity(intent);

            }
        });
        bulder.setNegativeButton("No", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Toast.makeText(ToolsManpowerHomeActivity.this, "Welldone", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }
        });

        AlertDialog d = bulder.create();
        d.show();

        break;
    case 4:

        break;

    default:
        break;
    }

}

From source file:com.richtodd.android.quiltdesign.app.QuiltEditActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quilt_edit);
    getActionBar().setDisplayHomeAsUpEnabled(true);

    m_quiltNameArgument = getIntent().getStringExtra(ARG_QUILT_NAME);

    if (savedInstanceState != null) {
        m_saveAsQuiltName = savedInstanceState.getString("saveAsQuiltName");
    }/*w w w. j a v  a 2s  .  c o m*/

    ActionBar ab = getActionBar();
    ab.setTitle("Edit Quilt");
    ab.setSubtitle(getCurrentQuiltName());

    FragmentManager fm = getFragmentManager();

    // Create color settings fragment.
    {
        Fragment fragment = fm.findFragmentById(R.id.layout_quiltEditFragment);
        if (fragment == null) {
            fragment = QuiltEditFragment.create(m_quiltNameArgument);
            fm.beginTransaction().add(R.id.layout_quiltEditFragment, fragment).commit();
        }
    }

    m_layout_blocks = (NestedLinearLayout) findViewById(R.id.layout_blocks);

    populateLayoutBlocks();
}

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

/**
 * Callback method to be invoked when an item in this AdapterView has been clicked.
 *
 * @param parent   The AdapterView where the click happened.
 * @param view     The view within the AdapterView that was clicked (this will be a view provided by the adapter)
 * @param position The position of the view in the adapter.
 * @param id       The row id of the item that was clicked.
 *//* w ww  .j  av  a2s. c  o m*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    activity.resetMovieDetailsBundle();
    activity.setRestoreMovieDetailsAdapterState(true);
    activity.setRestoreMovieDetailsState(false);
    activity.setOrientationChanged(false);
    activity.resetCastDetailsBundle();
    activity.resetTvDetailsBundle();
    if (tvDetails != null && lastVisitedTV == tvList.get(position).getId() && tvDetails.getTimeOut() == 0) {
        // Old movie details retrieve info and re-init component else crash
        tvDetails.onSaveInstanceState(new Bundle());
        Bundle bundle = new Bundle();
        bundle.putInt("id", tvList.get(position).getId());
        Bundle save = tvDetails.getSave();
        tvDetails = new TVDetails();
        tvDetails.setTimeOut(0);
        tvDetails.setSave(save);
        tvDetails.setArguments(bundle);
    } else
        tvDetails = new TVDetails();

    lastVisitedTV = tvList.get(position).getId();
    tvDetails.setTitle(tvList.get(position).getTitle());
    FragmentManager manager = getFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    Bundle bundle = new Bundle();
    bundle.putInt("id", tvList.get(position).getId());
    tvDetails.setArguments(bundle);
    transaction.replace(R.id.frame_container, tvDetails);
    // add the current transaction to the back stack:
    transaction.addToBackStack("TVList");
    transaction.commit();
    fragmentActive = true;
    activity.getTvSlideTab().showInstantToolbar();
}

From source file:hu.zelena.guide.MainActivity.java

@SuppressWarnings("ResourceType")
@Override/*from   w  w  w  .  j  av  a  2 s .  c om*/
protected void onCreate(Bundle savedInstanceState) {

    AnalyticsApplication application = (AnalyticsApplication) getApplication();
    mTracker = application.getDefaultTracker();

    /* user permissions krelmezs futsidben */
    ActivityCompat.requestPermissions(MainActivity.this, new String[] {
            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE },
            MY_PERMISSIONS_REQUEST_READ_STORAGE);

    ActivityHelper.initialize(this);

    isDark = ActivityHelper.darkMode(this);
    if (isDark) {
        Log.d("DarkTheme: ", "TRUE");
        setTheme(R.style.MainDarkTheme);
    } else {
        Log.d("DarkTheme: ", "False");
    }

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    if (sharedPrefs.getBoolean("offline", false)) {
        offlineMode = true;
    }
    if (sharedPrefs.getBoolean("betaMode", false)) {
        betaMode = true;
    }

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    CheckVersion();

    // Toolbar az ActionBar helyre
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // DrawerLayout belltsa
    mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerToggle = setupDrawerToggle();

    // Toogle belltsa
    mDrawer.addDrawerListener(drawerToggle);

    // DrawerView belltsa
    nvDrawer = (NavigationView) findViewById(R.id.nvView);
    setupDrawerContent(nvDrawer);

    Fragment fragment = new AboutFragment();
    if (fragment != null) {
        firstFrag = true;
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
    } else {
        Intent i = new Intent(this, ErrorActivity.class);
        i.putExtra("error", "Nem sikerlt a HOME-FRAGMENT betltse. [Null object]");
        startActivity(i);
        Log.e("MainActivity", "Error in creating fragment");
    }
}

From source file:com.example.sans.myapplication.Utility.Map.MapsActivity.java

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

    shares = getSharedPreferences("SHARES", 0);

    controller = (AppController) getApplication();

    receiver = new MyReceiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction("android.intent.action.test");
    this.registerReceiver(receiver, filter);

    Intent i = getIntent();/*from   ww w. j  a  v a 2  s.  c  om*/

    Bundle bundle = i.getExtras();

    try {
        j = new JSONObject(bundle.getString("data", "ERROR"));
        shares.edit().putString("ORDER", bundle.getString("data", "ERROR")).commit();
    } catch (JSONException e) {
        try {
            j = new JSONObject(shares.getString("ORDER", "ERROR"));
        } catch (JSONException e1) {
            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);
        }
    }

    try {
        Log.e("PHONE_NO", String.valueOf(j.getJSONObject("passenger_data")));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    pass_phone = (ImageView) findViewById(R.id.pass_phone);
    pass_phone.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent phoneIntent = null;
            try {
                phoneIntent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("tel:" + j.getJSONObject("passenger_data").getString("tel")));
            } catch (JSONException e) {
                e.printStackTrace();
            }

            startActivity(phoneIntent);
        }
    });
    pass_msg = (ImageView) findViewById(R.id.pass_msg);
    pass_msg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent msgIntent = new Intent(Intent.ACTION_VIEW);

            try {
                msgIntent.setData(Uri.parse("sms:" + j.getJSONObject("passenger_data").getString("tel")));
            } catch (JSONException e) {
                e.printStackTrace();
            }

            startActivity(msgIntent);
        }
    });

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

    setSupportActionBar(toolbar);

    TextView actionBarTitle = (TextView) toolbar.findViewById(R.id.action_bar_title);

    try {
        actionBarTitle.setText(j.getJSONObject("passenger_data").getString("family_name")
                + j.getJSONObject("passenger_data").getString("title"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    setUpMapIfNeeded();

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

    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(MapsActivity.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) {

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

                                pp_header.setImageBitmap(image);

                            }
                        });

                    }

                });
    } catch (JSONException e) {
        e.printStackTrace();
    }

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

            Intent i = new Intent(MapsActivity.this, MenuItemActivity.class);
            i.putExtra("MENU_ITEM", 0);
            MapsActivity.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(MapsActivity.this, MenuItemActivity.class);
                i.putExtra("MENU_ITEM", menuItem.getItemId());
                MapsActivity.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;
        }
    });

    // Initializing Drawer Layout and ActionBarToggle
    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);
        }
    };

    //Setting the actionbarToggle to drawer layout
    drawerLayout.setDrawerListener(actionBarDrawerToggle);

    //calling sync state is necessay or else your hamburger icon wont show up
    actionBarDrawerToggle.syncState();
}

From source file:com.blue.leaves.util.task.SugarTask.java

private void unregisterHookToContext(@NonNull Activity activity) {
    FragmentManager manager = activity.getFragmentManager();

    HookFragment hookFragment = (HookFragment) manager.findFragmentByTag(TAG_HOOK);
    if (hookFragment != null) {
        hookFragment.postEnable = false;
        manager.beginTransaction().remove(hookFragment).commitAllowingStateLoss();
    }/*  w  ww  . j a  va 2s .c o m*/
}

From source file:com.luan.thermospy.android.activities.MainActivity.java

@Override
public void onSetupServerConnectionEstablished(String ipAddress, int port, boolean running) {
    FragmentManager fragmentManager = getFragmentManager();
    ServerSettings serverSettings = Coordinator.getInstance().getServerSettings();
    serverSettings.setRunning(running);// w ww  .j  a v  a 2s  . c o  m
    serverSettings.setIpAddress(ipAddress);
    serverSettings.setPort(port);

    fragmentManager.beginTransaction()
            .replace(R.id.container,
                    SetupBoundary.newInstance(serverSettings.getIpAddress(), serverSettings.getPort()))
            .commit();

}

From source file:com.blue.leaves.util.task.SugarTask.java

private void registerHookToContext(@NonNull Activity activity) {
    FragmentManager manager = activity.getFragmentManager();

    HookFragment hookFragment = (HookFragment) manager.findFragmentByTag(TAG_HOOK);
    if (hookFragment == null) {
        hookFragment = new HookFragment();
        manager.beginTransaction().add(hookFragment, TAG_HOOK).commitAllowingStateLoss();
    }//from   w  w  w .ja v a2s . c om
}