Passing variable into onOptionsItemSelected - android

I'm pretty new to Android, so sorry if my problem seems basic. I spent all last night looking it up and couldn't find a solution (which makes me think I may have a fundamental flaw in what I'm trying to achieve).
Basically, I'm trying to call a method from inside onOptionsItemSelected. In the Android Developer documentation (http://developer.android.com/guide/topics/ui/menus.html) they give this example:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
newGame();
return true;
case R.id.help:
showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
However, in my application, I have methods called by onOptionsItemSelected that require an input. In the context of the example I'm using from the Android Developer website this would equate to me wanting to pass the integer "myint" to the newGame method:
#Override
public boolean onOptionsItemSelected(MenuItem item, int myint) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
newGame(myint);
return true;
case R.id.help:
showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
When I do this, Eclipse comes up with an error for the row "public boolean onOptionsItemSelected(MenuItem item) {" saying that I need to remove the "#Override" command.
I've not been able to find any examples on the internet where people are passing variables through onOptionsItemSelected (or methods like onConfigurationChanged) in this way, which is why I think I may have a fundamental misunderstanding in how this works. Unfortunately, I'm not really sure where to start with tackling this correctly. At the moment I'm using "public static" variables, so my methods (newGame in this example) can access them, but I realise the use of these type of variables seem to be generally frowned upon.
If anyone could help me with this or even point me in the direction of what I would need to search/read I would be very grateful.
Thanks
Stephen

You could have a private non-static variable in your class, and when you select the menu item, you can just read:
case R.id.new_game:
newGame(this.myint);
return true;
And have at the top of your class:
class MyActivity extends Activity {
private int myint;
You'll just have to make sure you have a value assigned to it before the user is clicking on the menu item!

Related

back button is faster than calling finish() in onOptionItemSelected menu

I have a simple activity with an image view and a simple menuItem which is used for came back in the previus activity.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I just realized that if I press the back button for coming back in the previous activity, android do it really fast, but pressing the menu item above, it waste a second. why?
The default way of doing a return back is
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
return super.onOptionsItemSelected(item);
}
}
By calling finish() you schedule the current activity for destruction, i.e. to call onDestroy(). This does some clean-up and thus produces an overhead and you experience therewith some latency. So, if you don't really have to use finish() there (e.g. to close some dialogs or cursors), just omit it and use the provided default solution.
Hope this helps!

Cannot invoke getItemId() on the primitive type boolean

I am new to android development and I have searched most of Menu option examples on the web. I am trying to handle a simple click event using "getItemId" and I get the following error :
Cannot invoke getItemId() on the primitive type boolean.
Here's the code :
public boolean onOptionsItemSelected(MenuItem menu)
{
// Handle Selection of Menu Items
switch (item.getItemId())
{
case(R.id.refresh):Toast.makeText(this, "Refresh", Toast.LENGTH_LONG).show();
break;
case(R.id.info):Toast.makeText(this, "Info", Toast.LENGTH_LONG).show();
break;
}
return true;
Thanks in advance for your help !
not this:
switch (item.getItemId())
but:
switch(menu.getItemId())
The reason this fails is just as the error says. Booleans are primitives, not objects. I am assuming somewhere above this excerpt is the line boolean item;. If you did a switch on a boolean the only possible cases would be true and false.
Instead of item, use menu - this is the menuItem passed to this method as a parameter.
And unfortunately, I don't know if *.getItemId() will work on a menuItem. I haven't tried it. If it doesn't, let me know, and I'll help ya find another way.

Android: return to main activity problems

In my main activity I have a menu and when a menu option is selected an Intent is created and a new activity is started. When that activity completes the process should return back to the main activity and all its previous states according to the ActivityLifeCycle.
I notice that when it returns back to the main activity, nothing is accessable and the screen dims. I can only get back to what I expect when I press the menu softkey.
Has anyone experienced this issue before? Feedback would be appreciated!
Code sample below:
#Override
protected void onResume(){
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_settings:
return true;
case R.id.menu_decks:
Intent launchDecks = new Intent(this, stackDecks.class);
startActivity(launchDecks);
return true;
case R.id.menu_exit:
this.onDestroy();
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
The code in the first post is actually correct(I have something very similar). There is a great chance the error is in the menu.xml res file, even though it inflates without any problems. Check it is fully consistent in both places, and has the same items. I finally solved it after hours of experimenting.
You seemed to be confused with the use of super.
super.m() is used to call a superclass method.
If you inherit the method with no override then
super.m() = this.m()
See your super.onDestroy
It s absoluetly useless to override a method m() just to call super.m()
See your onResume
Sometimes it is usefull to call a super clas method, it allows you to benefit from this code in a subclass. For instance here onCreateMenuOptions is overriden and your subclass can benefit from some imitialisation code for a menu.
Regards,
Stéphane

Should "android: onOptionsItemSelected" return true or false

In onOptionsItemSelected... I saw some code that are different in the switch block.
Case 1 (Normally seen)
public boolean onOptionsItemSelected (MenueItem item)
switch (item.getItemId()){
case R.id.item1:
startActivity (new Intent (this, PrefsActivity.class));
break;
}
return true
Case 2 (unsure of why it's set up this way)
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_NEW_GAME:
newGame();
return true;
}
return false;
My Question
What are the differences between Case 1 and Case 2?
Per the documentation for onOptionsItemSelected()
Returns
boolean Return false to allow normal
menu processing to proceed, true to
consume it here.
The if returned true the click event will be consumed by the onOptionsItemSelect() call and won't fall through to other item click functions. If your return false it may check the ID of the event in other item selection functions.
Your method will still work, but may result in unnecessary calls to other functions. The ID will ultimately fall through those functions since there is no switch to catch it, but return false is more correct.
As per documentation
true --> Event Consumed here, now It should not be forwarded for other event
false --> Forward for other event to get consumed
This boolean return type actually benefits when we are working with multiple fragments and every fragment has their own Options menu and override OnOptionItemSelected(Mainly in tablet design).
In this case android trace every fragment's OnOptionItemSelected() method, to avoid that
a) If any fragment is consuming event in onOptionsItemSelected() return "true"(to stop) else return "false"
b) If We return false then It will trace other connected fragment's onOptionsItemSelected() method until it ends all fragment or somebody consumes It.
Here I have tried to explain from diagram
Green color boundary is fragment-1 and Red color boundary is fragment-2
both fragment has their own Optionmenu which I have highlighted
Now If we click any of OptionmenuItem It will check Implementation of onOptionsItemSelected() in both fragments
If any fragment is consuming event onOptionsItemSelected return true, By this it would never try for other fragment and we can reduce overhead of Android operation system.
When I used Android Studio to generate a generic app, the template code for onOptionsItemSelected() returns true if item consumed otherwise it passes the call onto the super class.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_mymenuaction) {
return true;
}
return super.onOptionsItemSelected(item);
}
The problem with your method is that you return true even if your switch statement does not find an item. If you return true immediately like the other method for each switch case, then you can assume, if you are at the end of the method, that no switch cases were found, so return false to show that it was not handled.
I just had the problem that my
getActionBar().setDisplayHomeAsUpEnabled(true);
was not working. When touching the back button it would be highlighted but nothing happened.
It took me a while to figure out that this was the return of true.
In my opinion the best solution with less code duplication would be the following:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_NEW_GAME:
newGame();
break;
default:
return false;
}
return true;
}

What is the method on an onOptionsItemSelected menu in WebView for "forward" and "back" in Android?

I am trying to get my webView to move back and forward by calling up the menu. Thus far I have the menu working fine and opening, and the refresh button will refresh the browser. However, I cannot find documentation anywhere about the methods for forward of back. If the default internet browser has them by just pressing the menu key there must be out there. I just can't find them/don't know how to implement them. Any help would be beneficial, thank you.
Here is what I am trying to do:
WebView.Java:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_navigation, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.back_button:
"???"
case R.id.forward_button:
"???"
case R.id.refresh_button:
refreshBrowser();
return true;
}
return false;
}
The part that I'm missing is marked by the three question marks "???". Let me know if you need more information to get some help, and thanks again.
Use webView.canGoBack and webView.canGoForward to check if there is history data to go back / forward and then load that url.

Categories

Resources