i am using onCreateOptionsItem as shown below in the code, but when i overide onMenuItemSelected, it is marked with red. is there an alternative to it?how
can i fix this errors
code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem miRefrsh = menu.add(0, 1, 0,"refresh");
miRefrsh.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
//进入关于页面
MenuItem miScan = menu.add(0, 2, 1, "scan");
miScan.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
//退出系统
MenuItem miCancel = menu.add(0, 3, 2, "cancel");
miCancel.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
MenuItem miExit = menu.add(0, 4, 2, "exit");
miExit.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
return super.onCreateOptionsMenu(menu);
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case MEMU_RESCAN:
this.mGP.closeConn();
this.initActivityView();
this.openDiscovery();
return true;
case MEMU_EXIT:
this.finish();
return true;
case MEMU_ABOUT:
this.openAbout();
return true;
default:
return super.onMenuItemSelected(featureId, item);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// do Your Work Here
return super.onOptionsItemSelected(item);
}
Android knows about several types of menus (e.g. Options Menu and Context Menu). ''onMenuItemSelected'' is the generic callback. You don't need to use this usually. ''onOptionsItemSelected'' is the callback of the options menu and onContextItemSelected is the callback of the context menu.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) { //or switch-case
finish();
}
if (id == R.id.your_item1) {
}
if (id == R.id.your_item2) {
}
return super.onOptionsItemSelected(item);
}
SUDARSHAN is right. you can use onOptionsItemSelected.
use onOptionsItemSelected(MenuItem item) method and extend AppCompatActivity
In your case you should use menuItem.getTitle() and compare to the titles you programmatically added previously. Use menuItem.getId online when you're inflating a XML menu file. Hope this helps
Related
I am trying to hide the menu in the TableLayout with ViewPager I want the menu only in the solutions tab. I used the onPrepareOptionsmenu to hide the menu in tabs except the solutions tab. the thing is my onOptionsItemSelected is not working.
code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inf = getMenuInflater();
inf.inflate(R.menu.simpleadd,menu);
// +getMenuInflater().inflate(R.menu.simpleadd, menu);
onPrepareOptionsMenu(menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (viewpager.getCurrentItem()==0){
menu.findItem(R.id.simpleadd).setVisible(false);
} else if(viewpager.getCurrentItem()==1){
menu.findItem(R.id.simpleadd).setVisible(false);
} else if(viewpager.getCurrentItem()==2){
menu.findItem(R.id.simpleadd).setVisible(true);
} else if(viewpager.getCurrentItem()==3){
menu.findItem(R.id.simpleadd).setVisible(false);
}else if(viewpager.getCurrentItem()==4){
menu.findItem(R.id.simpleadd).setVisible(false);
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.simpleadd:
startActivity(new Intent(this,NewSolution.class));
}
return super.onOptionsItemSelected(item);
}
thanks in advance,
You have used the layout's name in the switch case of onOptionsItemSelected.
Use menu item's id instead.
First, you need to get item id and then set compare with layout ids,
this helps you to set the functionality. Please find the below sample
code for your reference.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.simpleadd) {
// execute your code here
}
return super.onOptionsItemSelected(item);
}
I am creating a menu, but both of menu options were intent to same class so how to fix this? Sorry I am a starter developer, so, please give me solution of that problem.
public void btnclick(View v){
openOptionsMenu();
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
menu.add(0, 1, 0, "What's in it");
menu.add(0, 2, 0,"send");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intt=new Intent(this,Help.class);
startActivity(intt);
return true;
}
Since you are adding 2 menu items at the onCreateOptionsMenu: 1st with ItemId = 1 and 2nd with ItemId = 2, you can use getItemId() to distinguish between menu items, like so:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case 1:
//do stuff like:
Intent intt=new Intent(this,Help.class);
startActivity(intt);
break;
case 2:
//do another stuff, like launching another activity
break;
default:
break;
}
return true;
}
Is there a way when a Menu item is clicked and before going to submenu we have to check a condition, if it is valid we launch the submenu if not we cancel. Please Help me I'm stuck with it ...
Thanks
okkk.. getting proble you should try like this..
public class Practice_TestActicvity extends Activity {
SubMenu sub;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("this is first menu");
menu.add("this is second menu");
sub = menu.addSubMenu(0, 1, 0, "SubMenu");
// sub.add(0,11,0,"SubMenu 1");
return super.onCreateOptionsMenu(menu);
}
and
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (item.getTitle().toString().equals("SubMenu")) {
sub.clear();
//you have to put here condtion like
//if(this==this){
Toast.makeText(this, "this is cliked", Toast.LENGTH_LONG).show();
sub.add(0, 11, 0, "SubMenu 1");
//}
//else{//execute this code
//}
}
return super.onMenuItemSelected(featureId, item);
}
now let me know which type of condition you wan to check?
Yes Ofcourse:
You can add/override onOptionsItemSelected(MenuItem item) method to get the results. See the example below:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.logout:
if(islogout){
//code if islogout is setted to true and procceed further for submenu
return true;
}else{
//code if islogout is setted to False and display Toast that could not procceed further.
return false;
}
default:
return super.onOptionsItemSelected(item);
}
}
I hope this helps.
Mark this answer Correct and with UpVote it it helps you!
Thanks
sHaH
Here I tried to make option menu, but menu is not displaying on screen, so please guide me where am I doing mistake...
MenuTest.java
public class MenuTest extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.more_tab_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.feeds:
break;
case R.id.friends:
break;
case R.id.about:
break;
}
return true;
}
}
And my XML file is more_tab_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/feeds"
android:title="Feeds"/>
<item
android:id="#+id/friends"
android:title="Friends"/>
<item
android:id="#+id/about"
android:title="About"/>
</menu>
Please guide me,
public class MenuTest extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.more_tab_menu, menu);
// return true so that the menu pop up is opened
return true;
}
}
and don't forget to press the menu button or icon on Emulator or device
please see :==
private int group1Id = 1;
int homeId = Menu.FIRST;
int profileId = Menu.FIRST +1;
int searchId = Menu.FIRST +2;
int dealsId = Menu.FIRST +3;
int helpId = Menu.FIRST +4;
int contactusId = Menu.FIRST +5;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(group1Id, homeId, homeId, "").setIcon(R.drawable.home_menu);
menu.add(group1Id, profileId, profileId, "").setIcon(R.drawable.profile_menu);
menu.add(group1Id, searchId, searchId, "").setIcon(R.drawable.search_menu);
menu.add(group1Id, dealsId, dealsId, "").setIcon(R.drawable.deals_menu);
menu.add(group1Id, helpId, helpId, "").setIcon(R.drawable.help_menu);
menu.add(group1Id, contactusId, contactusId, "").setIcon(R.drawable.contactus_menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
// write your code here
Toast msg = Toast.makeText(MainHomeScreen.this, "Menu 1", Toast.LENGTH_LONG);
msg.show();
return true;
case 2:
// write your code here
return true;
case 3:
// write your code here
return true;
case 4:
// write your code here
return true;
case 5:
// write your code here
return true;
case 6:
// write your code here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Change your onCreateOptionsMenu method to return true. To quote the docs:
You must return true for the menu to be displayed; if you return false it will not be shown.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.folderview_options, menu);
return (super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.locationListRefreshLocations) {
Cursor temp = helper.getEmployee(active_employeeId);
String[] matches = new String[1];
if (temp.moveToFirst()) {
matches[0] = helper.getEmployerID(temp);
}
temp.close();
startRosterReceiveBackgroundTask(matches);
} else if (item.getItemId()==R.id.locationListPrefs) {
startActivity(new Intent(this, PreferencesUnlockScreen.class));
return true;
}
return super.onOptionsItemSelected(item);
}
you can create options menu like below:
Menu XML code:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/Menu_AboutUs"
android:icon="#drawable/ic_about_us_over_black"
android:title="About US"/>
<item
android:id="#+id/Menu_LogOutMenu"
android:icon="#drawable/ic_arrow_forward_black"
android:title="Logout"/>
</menu>
How you can get the menu from MENU XML(Convert menu XML to java):
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my_options_menu,menu);
return super.onCreateOptionsMenu(menu);
}
How to get Selected Item from Menu:
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.Menu_AboutUs:
//About US
break;
case R.id.Menu_LogOutMenu:
//Do Logout
break;
}
return super.onOptionsItemSelected(item);
}
import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
public class AndroidWalkthroughApp2 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// show menu when menu button is pressed
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// display a message when a button was pressed
String message = "";
if (item.getItemId() == R.id.option1) {
message = "You selected option 1!";
}
else if (item.getItemId() == R.id.option2) {
message = "You selected option 2!";
}
else {
message = "Why would you select that!?";
}
// show message via toast
Toast toast = Toast.makeText(this, message, Toast.LENGTH_LONG);
toast.show();
return true;
}
}
Replace return super.onCreateOptionsMenu(menu); with return true; in your onCreateOptionsMenu method
This will help
And you should also have the onCreate method in your activity
The previous answers have covered the traditional menu used in android. Their is another option you can use if you are looking for an alternative
https://github.com/AnshulBansal/Android-Pulley-Menu
Pulley menu is an alternate to the traditional Menu which allows user to select any option for an activity intuitively. The menu is revealed by dragging the screen downwards and in that gesture user can also select any of the options.
Android UI programming is a little bit tricky. To enable the Options menu, in addition to the code you wrote, we also need to call setHasOptionsMenu(true) in your overriden method OnCreate().
Hope this will help you out.
IF your Device is running Android v.4.1.2 or before,
the menu is not displayed in the action-bar.
But it can be accessed through the Menu-(hardware)-Button.
Good Day
I was checked
And if You choose Empty Activity
You Don't have build in Menu functions
For Build in You must choose Basic Activity
In this way You Activity will run onCreateOptionsMenu
Or if You work in Empty Activity from start
Chenge in styles.xml the
I have made a simple app that just brings up an AlertDialog, with four items in the list. I register a context menu. When I long click one of the items, I get the context menu. I then select an item from the context menu, but onContextItemSelected never gets called. Any help? Thanks.
test.java:
package com.cerulean.tech.creations.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class test extends Activity {
private String[] files;
AlertDialog alert;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
files = new String[4];
}
public void selectScheme(View v) {
files[0] = "<New Scheme>";
files[1] = "test1";
files[2] = "test2";
files[3] = "test3";
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setItems(files, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
}});
alert = builder.create();
alert.show();
registerForContextMenu(alert.getListView());
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Context Menu");
menu.add(0, v.getId(), 0, "Delete");
menu.add(0, v.getId(), 0, "Cancel");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
return false;
}
}
In main.xml, I just a button defined with android:onClick="selectScheme"
After this line:
registerForContextMenu(alert.getListView());
type this:
alert.getListView().setOnCreateContextMenuListener(this);
And instead of onContextItemSelected(MenuItem item) function use this:
#Override
public boolean onMenuItemSelected(int featureId, MenuItem menuItem) {
The following function always gets executed.
public boolean onMenuItemSelected(int featureId, MenuItem menuItem)
But you can differentiate between context menus and option menus using the following flags:
if (featureId == Window.FEATURE_CONTEXT_MENU)
{
//Do something
}
else if (featureId == Window.FEATURE_OPTIONS_PANEL)
{
//Do something else
}
Just Add
#Override
public boolean onMenuItemSelected(int aFeatureId, MenuItem aMenuItem) {
if (aFeatureId==Window.FEATURE_CONTEXT_MENU)
return onContextItemSelected(aMenuItem);
else
return super.onMenuItemSelected(aFeatureId, aMenuItem);
}
I want to build on Miki's answer.
I only used
registerForContextMenu(this.getListView());
and
this.getListView().setOnCreateContextMenuListener(this);
in my parent ListActivity class.
I moved my code from the onContextItemSelected(MenuItem item) method to the onMenuItemSelected method.
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
try {
if (item.getItemId() == R.id.new_entry_menu_option) {
...
}
...
if (item.getItemId() == R.id.quit) {
/* perform cleanup */
...
return true;
} else if (item.getItemId() == R.id.delete_entry_context_menu_option) {
displayConfirmRequest(DELETE_CONFIRMATION_MESSAGE, item);
return true;
} else if (item.getItemId() == R.id.2ND_CONTEXT_OPTION) {
//code for 2nd option
return true;
} else if (item.getItemId() == R.id.3RD_CONTEXT_OPTION) {
//code for 3RD option
return true;
} else {
return super.onMenuItemSelected(featureId, item);
}// end if/else if/else
}// end try
catch (Exception error) {
//error handler code
return false;
}// end try/catch
}// end onMenuItemSelected
And make sure in your subclass, if you override onMenuItemSelected in the subclass of your super.ListActivity class, to include the following code if you want the contextmenu options to be handled in the super.class.
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (<condition>) {
...
} else {
return super.onMenuItemSelected(featureId, item);
}
}// end onMenuItemSelected
The real cause of this problem is that you're overriding onContextItemSelected and not calling super.onContextItemSelected. Change your onContextItemSelected method to this:
#Override
public boolean onContextItemSelected(MenuItem item) {
if (super.onContextItemSelected(MenuItem item))
return true;
return false;
}