1

In MainActivity I have the following method that launches fragments.

@Override
public void onNavigationItemSelected(MenuItem item) {
    int id = item.id;
    Fragment fragmentToShow = null;
    if (id != 1){
        fragmentToShow = MoviesFragment.newIstance(item);
    }
    if (fragmentToShow != null){
        launchFragment(fragmentToShow, null);
    }
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(Gravity.LEFT);
}

If the element with id = 1 is clicked, the application must open the main activity but it is not a fragment: how can i do it?

Thank you guys for your help, i am a beginner who tries to learn: surely it will be easy to solve this my problem

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
GiGa
  • 41
  • 7

2 Answers2

0

This method "onNavigationItemSelected" is being called from where?

As I understood this method comes from a Fragment and you wish to come back to the MainActivity, right?

When you say "MainActivity" means that it is the launch activity then you could use onBackPressed to go to previous Activity.

getActivity().onBackPressed();

If that's not the question, please complement with more details. It would be helpfull :)

Apolo
  • 81
  • 1
  • 1
  • 6
0

That is what you need

@Override
public void onNavigationItemSelected(MenuItem item) {
    int id = item.id;

    if (id == 1) {
        Intent intent = new Intent(getcontext(), MainActivity.class);
        startactivity(intent‌​);
        return;
    }

    Fragment fragmentToShow = null;
    if (id != 1){
        fragmentToShow = MoviesFragment.newIstance(item);
    }
    if (fragmentToShow != null){
        launchFragment(fragmentToShow, null);
    }
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(Gravity.LEFT);
}
eugeneek
  • 812
  • 9
  • 24
  • startActivity(new Intent(getApplicationContext(), MainActivity.class)) is perfect: I learn something and I forget another. Thank you so much. – GiGa Apr 25 '17 at 15:10
  • @GiGa Please accept answer if it was useful for you – eugeneek Apr 26 '17 at 07:52