Go from Main Activity to Fragment

0

I'm building an app on Android and it will have among the various activities a fragment for user profile.

The problem is that, from the selection of the profile, you need to go from the main activity to the fragment. But I'm having trouble with the transaction.

I do not know if I'm using it the wrong way or something, I'll leave the activity code:

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    int id = item.getItemId();

if (id == R.id.nav_Cadastrar)
  {
       Intent cadastrar = new Intent(NossaVozActivity.this, CadastroActivity.class);
       startActivity(cadastrar);
    }
    if (id == R.id.nav_Login)
    {
      Intent login = new Intent(NossaVozActivity.this, LoginActivity.class);
        startActivity(login);
    }
    else if (id == R.id.nav_Denuncia)
    {
        Intent denuncia = new Intent(NossaVozActivity.this, DenunciaActivity.class);
        startActivity(denuncia);
    }
    else if(id == R.id.nav_perfil)
   {
     Intent perfil = new Intent(NossaVozActivity.this,PerfilFragment.class);
      startActivity(perfil);
    }
    else if (id == R.id.nav_Sair)
    {

        {
        Intent fim = new Intent(NossaVozActivity.this, FimActivity.class);


        startActivity(fim);}

    }



    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
    
asked by anonymous 27.11.2018 / 12:26

1 answer

1

The problem is, startActivity() server to start an activity and not a fragment, to handle fragments you need a FragmentTransaction , to start your fragment you must do the following:

PerfilFragment perfilFrag = new PerfilFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.fragmentContainer, perfilFrag, perfilFrag.getTag()); //Você pode criar sua própria tag
ft.commit();

R.id.fragmentContainer is a View of your layout that you will use to show its fragments, add() adds the fragment to this View, if you want to replace the fragment you will use replace() , more information about creating and the use of fragments you can find in the documentation of android.

    
27.11.2018 / 13:32