I am new to android. I know this question have been asked before but, i am still confuse . What this method does when returning them inside my onCreateOptionMenu() and onOptionItemSelected()
Can any one help me what effect i will have
1)if i return true
2)if i return false
3)What will happen when i return super.onCreateOptionMenu() and super.onOptionItemSelected
Can anyone please explain me this with good example. I am still confuse.
Ok, let's first see the two methods of your interest
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
if return true ==>>> It means you want to see the option menu which you have inflated.
if return false ==>>> you do not want to show it
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
As per documentation
true --> Event Consumed now It should not be forwarded for other event
false --> Forward for other to consume
This Boolean return type actually benefits when we are working with multiple fragments and every fragment has their own Option menu and Overriding of OnOptionItemSelected(Mainly in tablet design)
In this case android trace every fragments OnOptionItemSelected method so to avoid that
a) If any fragment is consuming event in onOptionsItemSelected() so return "true" 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.
And your 3rd answer is as KrishnaJ written
super.onCreateOptionMenu() and super.onOptionItemSelected
If you write this then It will first call your parent class this method If you extend any class in this class.It will work as parent class if Methods are in parent class too.
Ok. I got you question:
Que 1 :
What this method does when returning them inside my onCreateOptionMenu() and onOptionItemSelected()
Ans :
onCreateOptionMenu() used for inflate menu in action bar.
onOptionItemSelected() used for capture onclick of that menus
Que 2 :
if i return true or false
Ans :
ref !!! you should return true if you have inflated menu in that file or your defined menu is clicked. else u should return false. so compiler will find for men or menu item in other page.
eg. you have one activity and two fragment, then if menu or menu item not find in activity then compiler will find it in fragment. if you return true then no further search.
Que 3 :
why to use super ?
Ans :
so compiler get to know that in this file there is no user defined menu or item value.
onCreateOptionMenu() method used to create an option menu.
onOptionsItemSelected() method used to handling the event of option menu i.e. which menu action is triggered and what should be the outcome of that action etc.
I like to add your 3rd question answer in answer of Dnyanesh
super.onCreateOptionMenu() and super.onOptionItemSelected
If you write this then It will first call your parent class this method If you extend any class in this class.It will work as parent class if Methods are in parent class too.
Related
I am new to android. I know this question have been asked before but, i am still confuse . What this method does when returning them inside my onCreateOptionMenu() and onOptionItemSelected()
Can any one help me what effect i will have
1)if i return true
2)if i return false
3)What will happen when i return super.onCreateOptionMenu() and super.onOptionItemSelected
Can anyone please explain me this with good example. I am still confuse.
Ok, let's first see the two methods of your interest
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
if return true ==>>> It means you want to see the option menu which you have inflated.
if return false ==>>> you do not want to show it
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
As per documentation
true --> Event Consumed now It should not be forwarded for other event
false --> Forward for other to consume
This Boolean return type actually benefits when we are working with multiple fragments and every fragment has their own Option menu and Overriding of OnOptionItemSelected(Mainly in tablet design)
In this case android trace every fragments OnOptionItemSelected method so to avoid that
a) If any fragment is consuming event in onOptionsItemSelected() so return "true" 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.
And your 3rd answer is as KrishnaJ written
super.onCreateOptionMenu() and super.onOptionItemSelected
If you write this then It will first call your parent class this method If you extend any class in this class.It will work as parent class if Methods are in parent class too.
Ok. I got you question:
Que 1 :
What this method does when returning them inside my onCreateOptionMenu() and onOptionItemSelected()
Ans :
onCreateOptionMenu() used for inflate menu in action bar.
onOptionItemSelected() used for capture onclick of that menus
Que 2 :
if i return true or false
Ans :
ref !!! you should return true if you have inflated menu in that file or your defined menu is clicked. else u should return false. so compiler will find for men or menu item in other page.
eg. you have one activity and two fragment, then if menu or menu item not find in activity then compiler will find it in fragment. if you return true then no further search.
Que 3 :
why to use super ?
Ans :
so compiler get to know that in this file there is no user defined menu or item value.
onCreateOptionMenu() method used to create an option menu.
onOptionsItemSelected() method used to handling the event of option menu i.e. which menu action is triggered and what should be the outcome of that action etc.
I like to add your 3rd question answer in answer of Dnyanesh
super.onCreateOptionMenu() and super.onOptionItemSelected
If you write this then It will first call your parent class this method If you extend any class in this class.It will work as parent class if Methods are in parent class too.
I have a Xamarin Android project that contains a menu bar. I'm almost certain this was working correctly yesterday, but since then, every time I click on a menu bar item such as 'settings', which takes me to the Settings Activity, then go back to the Main activity, the menu bar items are repeating themselves.
So where i just had 'Settings' and 'help', i not have 2 settings, and 2 help items. If i do it again, i will have 3 of each.
I'm assuming this is something to do with the onPause() and onResume() methods as the app goes to another activity. But i can't see where i'm going wrong (i'm new to Android)
My code for generating the menu bar in the Main Activity is:
public override bool OnPrepareOptionsMenu(IMenu menu1)
{
MenuInflater.Inflate(Resource.Menu.myMenuBar, menu1);
return base.OnPrepareOptionsMenu(menu1);
}
public override bool OnOptionsItemSelected(IMenuItem item) //do something when an options item is pressed
{
switch (item.ItemId)
{
case Resource.Id.settingsItem:
showSettings ();
return true;
case Resource.Id.helpItem:
//do something
return true;
}
return base.OnOptionsItemSelected(item);
}
Any ideas on this would be appreciated. I'm sure it's something fairly simple but I don't know what.
You should probably have to clear the menu
public override bool OnPrepareOptionsMenu(IMenu menu1)
{
menu1.clear();
MenuInflater.Inflate(Resource.Menu.myMenuBar, menu1);
return base.OnPrepareOptionsMenu(menu1);
}
And perhaps you should inflate the menu in the OnCreateOptionsMenu(IMenu, MenuInflater) method. OnPrepareOptionsMenu(IMenu) is meant for enabling/disabling and dynamically modifying items.
Im stuck and just exhausted, what am I doing wrong here and what do I need to do to get it to work right? Thanks
API 11.
I setup a item in menu.xml:
<item android:id="#+id/action_add_shindig"
**android:onClick="showCamera"**
android:icon="#drawable/shindig_new"
android:title="#string/shindig_new"
android:showAsAction="ifRoom" />
And in mainActivity I added a method to fire off an intent for the camera in another Activity.
/**
* Method to handle launching the Camera view activity.
* #param view
*/
public void showCamera(View view) {
}
But I get this error:
Couldn't resolve menu item onClick handler showCamera in class com.shindiggy.shindiggy.MainActivity
I resolved it by changing the method to onCameraClick(MenuItem item) and updating the onClick to reflect its name "onCameraClick".
It seems you already solved it, but this is something that has troubled me and is definitely something you would like to read the answer to in the actual documentation. (Just to make sure whatever fix you come up with works on all phones - not just your own...)
Look here: https://developer.android.com/guide/topics/resources/menu-resource#item-element
The android:onClick property of a item in the menu needs a public method with MenuItem as its parameter.
Note that this is different from, say, a Button!
http://developer.android.com/reference/android/widget/Button.html
http://developer.android.com/reference/android/R.attr.html#onClick
Here, a method taking View as its parameter is needed.
I don't believe menuItem has an onClick(). Use onOptionsItemSelected instead. Use themenuItemid` to know which item was clicked.
Menu Docs
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_add_shindig:
// run your showCamera code or call that method
return true;
Handling click events
That is for an OptionsMenu but it also discusses ContextMenus
dont use OnClick Method .
use if statement in Method below:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
else if (id==R.id.action_other)
{
Toast toast=Toast.makeText(this, "Other Clicked.", Toast.LENGTH_LONG);
toast.show();
}
else if (id==R.id.action_Exit)
{
finish();
}
return super.onOptionsItemSelected(item);
}
According to Android Doc - https://developer.android.com/guide/topics/resources/menu-resource#item-element
android:onClick
Method name. The method to call when this menu item is
clicked. The method must be declared in the activity as public and
accept a MenuItem as its only parameter, which indicates the item
clicked. This method takes precedence over the standard callback to
onOptionsItemSelected(). See the example at the bottom.
Warning: If
you obfuscate your code using ProGuard (or a similar tool), be sure to
exclude the method you specify in this attribute from renaming,
because it can break the functionality.
Introduced in API Level 11.
I have an activity which can contain several fragments. Each of the fragments can have their own menu entries in the ActionBar. This works fine so far and each item is clickable and performs the desired action.
My problem is the following. In the MainActivity I declared the following lines to intercept calls to the HomeIcon of the ActionBar:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
clearBackStack();
setHomeFragment();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I declared it in the Activity because I wanted that every Fragment should call this so that I don't have to catch the android.R.id.home case in each fragment.
In one Fragment I am using setDisplayHomeAsUpEnabled(true), so that I get the little arrow left of the ActionBar Icon. When the HomeIcon is clicked in this fragment I don't want to set the HomeFragment, I want to set the Fragment which was last displayed. So I have a onOptionsItemSelected - Method in the Fragment:
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
setLastFragment();
return true;
...
However this does not work the way I wanted it to work. The Activity's onOptionsItemSelected is called first, catches the MenuItem and redirects to the HomeFragment. With the other MenuItems declared in other fragments i can check the see the same behaviour. Activity is called first, doesn't catch the MenuItem (default case) and then redirects to super.onOptionsItemSelected(item).
So it seems that this is the case how Android handles the Menu Clicks. First Activity, then Fragment. Is there a way to change this? I don't want to put the android.R.id.home-case in every fragment and handle it there. Is there a nicer way to do this?
I just encounter this problem, and I have made it work using following code.
In the activity's onOptionsItemSelectedfunction, add:
if (id == android.R.id.home){
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.container);
if(null != currentFragment && currentFragment.onOptionsItemSelected(item)){
return true;
}
}
And in the fragment's onOptionsItemSelected method, you handle the corresponding things.
In this way, if the fragment has any things to do for the menu item, it will do it and return true to stop any other process.
And if the fragment does not have anything to do with this item, it will return false or call super.onOptionsItemSelected method which may eventually return false to let others process it.
According to the developers reference,
"Return false to allow normal menu processing to proceed, true to consume it here."
So I would try returning 'false' by default in the Activity's implementation of onOptionsItemSelected(), this way the event will pass on to the Fragment's implementation if it is not caught.
Not sure if it's possible. In the official docs available here:
http://developer.android.com/guide/topics/ui/actionbar.html#ActionEvents
There is a note, that states the following:
[...] However, the activity gets a chance to handle the event first, so the system first calls onOptionsItemSelected() on the activity, before calling the same callback for the fragment.
You can do as #Surely written, it's great idea, but in that case you will call onOptionsItemSelected on fragment without knowing which fragment it is, and you should override onOptionsItemSelected method in all your fragments.
If you only want to call this method for particular fragments, you should find them by tag, which you used when adding them:
case android.R.id.home:
Fragment frag = getSupportFragmentManager()
.findFragmentByTag(FRAGMENT_TAG);
if(frag != null && frag.isVisible() && frag.onOptionsItemSelected(item)) {
return true;
Tag is specifying like this:
fragmentManager.beginTransaction()
.add(containerId, fragment, FRAGMENT_TAG)
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;
}