Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onNavigationItemSelected in ActionBar is being called at startup how can avoid it?

I am using ActionBar with a dropdown menu, and onNavigationItemSelected() is called as soon as the Activity is created, so the first item is called. The first item of my dropdown menu is Home, the same action as pressing the application icon with android.R.id.home so when application starts it calls itself. To avoid this from happening I have this code:

if(this.getClass() != FrecView.class){  //if i am not currently on the Activity
    Intent frec = new Intent(this, FrecView.class);
    frec.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(frec);
}

But i have ActionBar on all my activities so every time every activity is started it calls itself forever so I have to put that code for each activity. What is happening? How can i prevent this from happening?

like image 279
Andres Avatar asked Apr 15 '12 23:04

Andres


2 Answers

As Mark has stated, its not designed to be a menu.

However, here is a quick and dirty approach to ignore the first call:

declare this class field:

//mNaviFirstHit should be initialized to true
private boolean mNaviFirstHit = true;

And in the onNavigationItemSelected:

@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
    if (mNaviFirstHit) {
        mNaviFirstHit = false;
        return true;
    }
    // DO WHAT YOU WOULD NORMALLY DO
}
like image 94
Iraklis Avatar answered Oct 30 '22 13:10

Iraklis


i am using ActionBar whit a dropdown menu and onNavigationItemSelected() is called as soon Activity is created

This is not designed to be a "menu", any more than tabs are designed to be a "menu". The list navigation is designed to allow the user to indicate some content for the current activity, typically by replacing a fragment. Action items (e.g., toolbar buttons, action spillover area) are for navigating between activities.

The first item of my dropdown menu is Home the same action as pressing the application icon whit android.R.id.home so when application starts it calls itself.

So, delete that from your "menu". The user can press your app icon on the left to navigate home.

like image 24
CommonsWare Avatar answered Oct 30 '22 15:10

CommonsWare