Go from main activity to fragment

Asked

Viewed 94 times

0

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

The problem is that it would need, from the profile selection, to go from the main Activity to the Fragment. But I’m having trouble with the transaction.

I don’t know if I’m using the Internet the wrong way or something, I’m gonna leave Activity’s 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;
}
  • Welcome to the community! What is the problem that is occurring? The application breaks when you try to go to another Activity?

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 your fragments, add() adds the fragment to this View, if you want to replace the fragment you will use replace(), more information about the creation and use of the fragments you can find in documentation android.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.