Make menu item on android work like a button - android

I'm here to see if they guide me in this problem
I have a menu, with an item, and what I want is that item to work as a button, if you click on it change the icon and a toast that says Notification active, and if you click again, change the icon and say using toast, Disabled notifications.
All this I have achieved, the detail is that when activating the button and leaving the activity and when entering again, the button is again deactivated, when it should be activated
I hope you understand, here I give you the code, which makes the function perfect, but I think I must do something with shared preferences to save if it is clicked or not, but I do not know where to start, I hope you understand and guide me, I leave the code that I have implemented
----- xml menu ------------
<?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:icon="#drawable/ic_notifications_off_black_24dp"
android:title="#string/notificaciones"
android:id="#+id/notificaciones"
android:checkable="true"
app:showAsAction="always"
/>
</menu>
--------- Java---------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menucampeonatos, menu);
MenuItem item = menu.findItem(R.id.notificaciones);
item.setChecked(false);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem checkable = menu.findItem(R.id.notificaciones);
checkable.setChecked(false);
return super.onPrepareOptionsMenu(menu);
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.notificaciones:
if (item.isChecked()){
myRef.update("notificacion", false);
item.setChecked(false);
item.setIcon(R.drawable.ic_notifications_off_black_24dp);
Toast.makeText(this, "Notificaciones Desactivadas para este campeonato", Toast.LENGTH_LONG).show();
}else{
myRef.update("notificacion", true);
item.setChecked(true);
item.setIcon(R.drawable.ic_notifications_active_black_24dp);
Toast.makeText(this, "Notificaciones Activadas para este campeonato", Toast.LENGTH_LONG).show();
}
return true;
}
return super.onOptionsItemSelected(item);
}

First you need to implement Shared Preferences, as you mentioned
private String sharedPrefFile = "your Shared Preferences Name";
private String NOTIFICATION_KEY = "notification_key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPreferences = getSharedPreferences(sharedPrefFile, MODE_PRIVATE);
...
}
Then, in your onOptionsItemSelected, you need to save user action to preference
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.notificaciones:
if (item.isChecked()){
// Add this line
SharedPreferences.Editor preferencesEditor = mPreferences.edit();
preferencesEditor.putBoolean(NOTIFICATION_KEY, true);
preferencesEditor.apply();
myRef.update("notificacion", false);
item.setChecked(false);
item.setIcon(R.drawable.ic_notifications_off_black_24dp);
Toast.makeText(this, "Notificaciones Desactivadas para este campeonato", Toast.LENGTH_LONG).show();
}else{
// Add this line
SharedPreferences.Editor preferencesEditor = mPreferences.edit();
preferencesEditor.putBoolean(NOTIFICATION_KEY, false);
preferencesEditor.apply();
myRef.update("notificacion", true);
item.setChecked(true);
item.setIcon(R.drawable.ic_notifications_active_black_24dp);
Toast.makeText(this, "Notificaciones Activadas para este campeonato", Toast.LENGTH_LONG).show();
}
return true;
}
return super.onOptionsItemSelected(item);
}
Lastly, load the preference everytime activity is destroyed in onPrepareOptionsMenu
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem checkable = menu.findItem(R.id.notificaciones);
String isNotificationClicked = mPreferences.getBoolean(NOTIFICATION_KEY, false);
checkable.setChecked(isNotificationClicked);
return super.onPrepareOptionsMenu(menu);
}

Related

open a menu from OnClickListener

I want to open a menu from a OnClickListener
without using the method onCreateOptionsMenu
My code:
toolbar.setNavigationIcon(R.drawable.week); //your icon
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v ) {
}
});
Thanks in advance!
I think you want to show/hide a menu item based on actions from users. To do that you must use onCreateOptionsMenu and whenever you want to show/hide the menu item, then call invalidateOptionsMenu (this method will call onCreateOptionsMenu again).
boolean mShowMenu = false;
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.your_menu, menu);
MenuItem item = menu.findItem(R.id.your_menu_item);
item.setVisible(showMenu);
return true;
}
And in your code, when you want to show menu item.
toolbar.setNavigationIcon(R.drawable.week); //your icon
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v ) {
mShowMenu = true;
invalidateOptionsMenu();
}
});
And give it a try.
You should need to create menu Interface in xml File Like this
<item
android:id="#+id/settings"
android:title="Setting"
app:showAsAction="never" />
<item
android:id="#+id/my_activity"
android:title="My Activity"
app:showAsAction="always"
android:icon="#android:drawable/btn_radio"/>
After that in the Java code of a particular class You need to create the code like this;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.my_activity) {
Intent intent1 = new Intent(this,MyActivity.class);
this.startActivity(intent1);
return true;
}
if (id == R.id.settings) {
Toast.makeText(this, "Setting", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
Hopefully this may resolve your problem

Recall, onCreateOptionsMenu method (more times)

I have this problem: in my class.java I have a private method (I call this in onRemoteCallListenerComplete) that elaborate a data that I want to appear in Menu. This method is not very fast and the application call the onCreateOptionsMenu method before onRemoteCallListenerComplete is finished.
I have read the use void invalidateOptionsMenu() method - to invalidate and re-call onCreateOptionsMenu - and I append this before onRemoteCallListenerComplete ended. However, onOptionsItemSelected method is not re-called.
NB: I'm sorry for my (terrible) English
The following i put my code
onCreateOptionsMenu method
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.dati_carriera, menu);
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
MenuItem item = menu.findItem(R.id.expandableListView1_checkable);
if(sizeValueCollection>0){
item.setVisible(false);
}else{
boolean value = prefs.getBoolean(PREFERENCE_EXPANDIBLE_LIST_VIEW, true);
if(value)
item.setChecked(true);
else
item.setChecked(false);
}
return super.onCreateOptionsMenu(menu);
}
onOptionsItemSelected method
#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.
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
Toast.makeText(this, "onOptionItemSelceted", Toast.LENGTH_LONG).show();
final ExpandableListView tv;
int id=item.getItemId();
switch(id){
case R.id.expandableListView1_checkable:
tv = (ExpandableListView) findViewById(R.id.expandableListView1);
if(item.isChecked()){
item.setChecked(false);
tv.setVisibility(ExpandableListView.GONE);
Editor prefsEditor = prefs.edit();
prefsEditor.putBoolean(PREFERENCE_EXPANDIBLE_LIST_VIEW, false);
prefsEditor.commit();
}else{
item.setChecked(true);
tv.setVisibility(ExpandableListView.VISIBLE);
Editor prefsEditor = prefs.edit();
prefsEditor.putBoolean(PREFERENCE_EXPANDIBLE_LIST_VIEW, true);
prefsEditor.commit();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
onRemoteCallListenerComplete
#Override
public void onRemoteCallListenerComplete(String dati) {
// TODO Auto-generated method stub
[...]
sizeValueCollection=valueCollection.size();
invalidateOptionsMenu();
}
sizeValueCollection is a private int variable initialized to -1
try supportInvalidateOptionsMenu() if you use activity from support package
You can keep a reference to Menu object and update it after you receive all required data.
public class MyActivity extends Activity {
private Menu menu;
private MyMenuData myMenuData;
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
// Prepare menu
this.menu = menu;
if(myMenuData != null){
// Data is loaded, menu can be updated now
updateMenu(myMenuData);
}
return super.onCreateOptionsMenu(menu);
}
public void onRemoteCallListenerComplete(MyMenuData data){
this.myMenuData = data;
updateMenu(data);
}
private void updateMenu(MyMenuData menuData){
// Update your menu here
}
}

How to save instance state of selected radiobutton on menu

I have options menu in my toolbar with radibutton item :
<item
android:id="#+id/map_menu"
android:icon="#drawable/ic_layer"
android:orderInCategory="102"
app:showAsAction="always"
android:title="#string/action_settings">
<menu>
<group
android:id="#+id/map_types_group"
android:checkableBehavior="single" >
<item
android:id="#+id/map_terrain"
android:orderInCategory="1"
app:showAsAction="ifRoom"
android:title="#string/map_terrain"/>
<item
android:id="#+id/map_normal"
android:orderInCategory="2"
android:checked="true"
app:showAsAction="ifRoom"
android:title="#string/map_normal"/>
<item
android:id="#+id/map_hybrid"
android:orderInCategory="3"
app:showAsAction="ifRoom"
android:title="#string/map_hybrid"/>
</group>
</menu>
</item>
I want to restore selected radiobutton when orientation change happened in onSaveInstanceState,onRestoreInstanceState but i can't understand how to get selected button from radiogroup in options menu.
Here is a fully working and tested example. With this code in place, no matter how many times you rotate the screen, the currently selected item will persist.
First, create these instance variables to keep track of the state of the menu and have a name for the preference you will be saving in the Bundle:
private final static String MENU_SELECTED = "selected";
private int selected = -1;
MenuItem menuItem;
The saveInstanceState() method should save off the currently selected value:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt(MENU_SELECTED, selected);
super.onSaveInstanceState(savedInstanceState);
}
Update the currently selected item in onOptionsItemSelected():
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Log.d("settings", "id: " + id);
return true;
}
if (id == R.id.map_terrain){
Log.d("menuitem", "terrain id: " + id);
selected = id;
item.setChecked(true);
return true;
}
if (id == R.id.map_normal){
Log.d("menuitem", "normal id: " + id);
selected = id;
item.setChecked(true);
return true;
}
if (id == R.id.map_hybrid){
Log.d("menuitem", "hybrid id: " + id);
selected = id;
item.setChecked(true);
return true;
}
return super.onOptionsItemSelected(item);
}
In onCreate(), load the saved data if it exists:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null){
selected = savedInstanceState.getInt(MENU_SELECTED);
}
}
And then re-select the previously selected item in onCreateOptionsMenu():
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
if (selected == -1){
return true;
}
switch (selected){
case R.id.map_terrain:
menuItem = (MenuItem) menu.findItem(R.id.map_terrain);
menuItem.setChecked(true);
break;
case R.id.map_normal:
menuItem = (MenuItem) menu.findItem(R.id.map_normal);
menuItem.setChecked(true);
break;
case R.id.map_hybrid:
menuItem = (MenuItem) menu.findItem(R.id.map_hybrid);
menuItem.setChecked(true);
break;
}
return true;
}
MenuItem in onOptionsItemSelected has item.isChecked() method, just use it. You can store one boolean field(it wouldn't be a bad thing in my opinion) and change it whenever change in radiog group occurs
Then you can have your id by simply calling:
if(item.isChecked()) {
your_id_field = item.getItemId()
}
Create a variable eg: menu_selection to store the id of the menu item selected. Initially you can define 0
private int menu_selection = 0;
Save and restore the value of the variable using onSaveInstanceState and onRestoreInstanceState
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the id of radio button selected in the menu
savedInstanceState.putInt("selection", menu_selection);
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
menu_selection = savedInstanceState.getInt("selection");
}
In onOptionsItemSelected , assign the id of the menu item selected item.getItemId() to the variable
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
if (item.isChecked()) {
item.setChecked(false);
} else {
item.setChecked(true);
menu_selection = item.getItemId();
}
switch (item.getItemId()) {
case R.id.map_terrain:
//some action here
return true;
case R.id.map_normal:
//some action here
return true;
case R.id.map_hybrid:
//some action here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
In onCreateOptionsMenu , find the menu item identified with the value in the variable and check it
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
if (menu_selection != 0) {
MenuItem selected = (MenuItem) menu.findItem(menu_selection);
selected.setChecked(true);
}
return true;
}

How can I dynamically create menu items?

I'm building an Android application and I'm trying to build a user management system where users can login, logout, etc. I want to display a login menu item if the user is logged out and a logout button if the user is logged in. How can I do this dynamically?
This is the layout file right now:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/add" android:title="Add" android:icon="#drawable/ic_menu_add"/>
<item android:id="#+id/list" android:title="List" android:icon="#drawable/ic_menu_list"/>
<item android:id="#+id/refresh" android:title="Refresh" android:icon="#drawable/ic_menu_refresh"/>
<item android:id="#+id/login" android:title="Login" android:icon="#drawable/ic_menu_login"/>
</menu>
This is my Java right now:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.activity_main, menu);
return(super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
System.out.println(item.getItemId()==R.id.add);
if (item.getItemId()==R.id.add)
{
//Cannot add spot unless we have obtained the users current location.
if((currentLat != 0) && (currentLng != 0))
{
System.out.println("loggedin? : " + auth.isLoggedIn());
if(!auth.isLoggedIn())
{
Toast.makeText(MainActivity.this, "You must be logged in to add a new spot",
Toast.LENGTH_LONG).show();
}
else
{
Intent addIntent = new Intent(MainActivity.this, AddSpot.class);
Bundle b = new Bundle();
b.putDouble("currentLat", currentLat);
b.putDouble("currentLng", currentLng);
addIntent.putExtras(b);
startActivity(addIntent);
return(true);
}
}
}
else if(item.getItemId()==R.id.list)
{
//Pointless showing them a blank screen if nothing is retrieved from the server
if(list != null)
{
Intent listIntent = new Intent(MainActivity.this, ListLocations.class);
listIntent.putExtra("list", list);
startActivity(listIntent);
return(true);
}
}
if(item.getItemId()==R.id.refresh)
{
finish();
startActivity(getIntent());
return(true);
}
if(item.getItemId()==R.id.login)
{
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
return(true);
}
return(super.onOptionsItemSelected(item));
}
How to Dynamically Add Menu Items to an Android Activity
public class yourActivity extends Activity {
...
private static final int MENU_ADD = Menu.FIRST;
private static final int MENU_LIST = MENU.FIRST + 1;
private static final int MENU_REFRESH = MENU.FIRST + 2;
private static final int MENU_LOGIN = MENU.FIRST + 3;
/**
* Use if your menu is static (i.e. unchanging)
*/
/*
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_ADD, Menu.NONE, R.string.your-add-text).setIcon(R.drawable.your-add-icon);
menu.add(0, MENU_LIST, Menu.NONE, R.string.your-list-text).setIcon(R.drawable.your-list-icon);
menu.add(0, MENU_REFRESH, Menu.NONE, R.string.your-refresh-text).setIcon(R.drawable.your-refresh-icon);
menu.add(0, MENU_LOGIN, Menu.NONE, R.string.your-login-text).setIcon(R.drawable.your-login-icon);
return true;
}
*/
/**
* Gets called every time the user presses the menu button.
* Use if your menu is dynamic.
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
if(enableAdd)
menu.add(0, MENU_ADD, Menu.NONE, R.string.your-add-text).setIcon(R.drawable.your-add-icon);
if(enableList)
menu.add(0, MENU_LIST, Menu.NONE, R.string.your-list-text).setIcon(R.drawable.your-list-icon);
if(enableRefresh)
menu.add(0, MENU_REFRESH, Menu.NONE, R.string.your-refresh-text).setIcon(R.drawable.your-refresh-icon);
if(enableLogin)
menu.add(0, MENU_LOGIN, Menu.NONE, R.string.your-login-text).setIcon(R.drawable.your-login-icon);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case MENU_ADD: doAddStuff(); break;
case MENU_LIST: doListStuff(); break;
case MENU_REFRESH: doRefreshStuff(); break;
case MENU_LOGIN: doLoginStuff(); break;
}
return false;
}
The following specific example adds a MENU_LOGOUT option if the user is logged in.
private static final int MENU_LOGOUT = MENU.FIRST + 4;
public boolean onPrepareOptionsMenu(Menu menu) {
...
if(auth.isLoggedIn()) {
menu.add(0, MENU_LOGOUT, Menu.NONE, R.string.your-logout-text).setIcon(R.drawable.your-logout-icon);
}
...
}
public boolean onOptionsItemSelected(MenuItem item) {
...
case MENU_LOGOUT:
if(auth.isLoggedIn()) {
doLogout();
} else {
Toast.makeText(this, "You must have somehow been logged out between the time the menu button was pressed and now.", Toast.DURATION_LONG).show();
}
break;
...
}
That's all there is to it.
In my case the menu items are in the ArrayList , - try this Hope it will help u :)
public void onClick(View v)
{
PopupMenu menu = new PopupMenu(DialogCheckBox.this, v);
for (String s : limits) { // "limits" its an arraylist
menu.getMenu().add(s);
}
menu.show();
}
you can call invalidateOptionsMenu() (note:need to use compatability library like actionBarSherlock to access in case you need to support low API versions) , and then update the menu items according to the status.
there you could hide the login action item and show the logout action item.
you might also try update the icon itself but i never tried it.
private void getPopup(final TextView textView, ArrayList<String> arrayList) {
final PopupMenu popupMenu = new PopupMenu(sContext, textView);
for (int i = 0; i < arrayList.size(); i++) {
popupMenu.getMenu().add(arrayList.get(i));
}
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
textView.setText(item.getTitle());
return false;
}
});
popupMenu.show();
}
Simple way to create menu items :
Dynamic_PopUpMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu menu = new PopupMenu(DialogCheckBox.this, v);
menu.getMenu().add("AGIL"); // menus items
menu.getMenu().add("AGILANBU"); // menus items
menu.getMenu().add("AGILarasan");
menu.getMenu().add("Arasan");
menu.show();
}
});
Try this :)
it's so easy
To create the menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
for (int i = 0; i < list.size(); i++) {
menu.add(0, i, 0, "Menu Name").setShortcut('5', 'c');
}
return true;
}
to get the details from clicked menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId(); //to get the selected menu id
String name = item.getTitle(); //to get the selected menu name
return super.onOptionsItemSelected(item);
}

Android, How to create option Menu

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

Categories

Resources