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?
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:
And in the onNavigationItemSelected:
You can force the correct default option in your "menu" with the following:
Counter-intuitively this must be done AFTER setting the callbacks (which to my mind would give the callback a chance to fire with navigation index of 0). For example, my app has two activities ListView and PageView, and I like my navigation menu ordered alphabetically, but the default start-up activity is PageView. So I have the following in PageView's onCreate():
and in ListView's onCreate():
Then, no matter how many times I call startActivity(otherView), it will always set the navigation menu correctly.
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.
So, delete that from your "menu". The user can press your app icon on the left to navigate home.
First of all thanks to @CommonsWare for reminding us it is an alternative to tabs, so the code should be designed with that perspective. Though it is not as straight forward as it appears, nevertheless we can work around there.
This can be avoided using a flag as well. But, anyways i suggest the approach i took to fix this.
Just make sure it's called once. Besides that make it an inner class than an anonymous. That will prevent it being called every time this part of code is executed. code below:
And i see a strange event here, if i make it an inner class it doesn't call onNavigationItemSelected(), if we make it an anonymous class, it will fire onNavigationItemSelected method. If anyone can throw some light on this, it will be useful.