Surender Singh Lamba Surender Singh Lamba - 2 years ago 95
Android Question

Loop due to intents in navigation drawer

I have extended my newActivity to mainActivity fine and I got the navigation drawer working, but now it sort of forms a loop as it again picks up the click of newActivity in navigation drawer and opens up a new intent again,so basically I am opening intent inside intent inside intent, I want to move between items in drawer and not open a new intent for every click, what am I doing wrong?

My navigation Drawer(below) Listening for click event and opens a activity called main acitvity

public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == {
startActivity(new Intent(Main2Activity.this, MainActivity.class));
} else if (id == {

} else if (id == {

} else if (id == {

} else if (id == {

} else if (id == {


DrawerLayout drawer = (DrawerLayout) findViewById(;
return true;

Now as this drawer will also come with main activity as I have extended it from the activity with drawer, I get the option of clicking on the mainactivity option in new intent again, so this sort of gives me ability to open mainActivity any number of times, i dont want this

Answer Source

You should use fragments. Activity holds your main view and your activity drawer seperately. When you click some item in drawer, just replace your fragment on main container.

Check this :


public void replaceFragment(Fragment fragment) {
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.replace(, fragment);

put this method into your activity. And create a FrameLayout in your Main Layout.



Now you can set a fragment in onCreate() for the first screen using replaceFragment(Blala.newInstance()). When you click and item on Drawer just call replaceFragment(...) again.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download