Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

android - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...