I'd like to customize options menu in my app. After some googling and making a lot of effort I am still unable to do it. Here is what I want:
menu.xml file:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/menu_first"
android:icon="#drawable/phone_selector"
android:title="#string/first"/>
<item
android:id="#+id/menu_second"
android:icon="#drawable/butterfly_selector"
android:title="#string/second"/>
<item
android:id="#+id/menu_third"
android:icon="#drawable/umbrella_selector"
android:title="#string/third"/>
</menu>
OptionsMenuActivity.java:
public class OptionsMenuActivity extends Activity {
private Menu currentMenu;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu, menu);
this.currentMenu = menu;
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
setMenuItemIconState(menu, MyApplication.getSelectedMenuItemDrawIcon(), false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_phone:
setMenuItemIconState(currentMenu, MyApplication.getSelectedMenuItemDrawIcon(), true);
MyApplication.setSelectedMenuItemDrawIcon(R.drawable.phone_active);
Intent intent = new Intent(OptionsMenuActivity.this, FirstActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.menu_butterfly:
setMenuItemIconState(currentMenu, MyApplication.getSelectedMenuItemDrawIcon(), true);
MyApplication.setSelectedMenuItemDrawIcon(R.drawable.butterfly_active);
intent = new Intent(OptionsMenuActivity.this, SecondActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.menu_umbrella:
setMenuItemIconState(currentMenu, MyApplication.getSelectedMenuItemDrawIcon(), true);
MyApplication.setSelectedMenuItemDrawIcon(R.drawable.umbrella_active);
intent = new Intent(OptionsMenuActivity.this, ThirdActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setMenuItemIconState(Menu menu, int menuItemIconRes, boolean switchLastActiveMenuItemIcon) {
int menuItemId = 0;
int lastDeActiveDrawIcon = 0;
switch (menuItemIconRes) {
case R.drawable.phone_active:
menuItemId = R.id.menu_first;
lastDeActiveDrawIcon = R.drawable.phone;
break;
case R.drawable.butterfly_active:
menuItemId = R.id.menu_second;
lastDeActiveDrawIcon = R.drawable.butterfly;
break;
case R.drawable.umbrella_active:
menuItemId = R.id.menu_third;
lastDeActiveDrawIcon = R.drawable.umbrella;
break;
}
if (switchLastActiveMenuItemIcon) {
MenuItem menuItem = menu.findItem(menuItemId);
menuItem.setIcon(lastDeActiveDrawIcon);
return;
}
MenuItem menuItem = menu.findItem(menuItemId);
menuItem.setIcon(MyApplication.getSelectedMenuItemDrawIcon());
}
}
In MyApplication.java I have only a getter and a setter of selectedMenuItemDrawIcon.I managed to set the icons properly, but failed with the others.
Is it possible to customize options menu like that? If not, is there any other approaches for creating an xml file and make it appear and disappear smoothly just like basic menu of android.
Any help would be appreciated. Thanks in advance, (please provide with code example).
Related
So I have a menu with 2 items set on it in res/menu/menu_item.xml. I want to add on onClick method to the Menu Item but where do I put the method? I have the menu_item set on 3 different activities but I want one universal method which is called by the onClick method in the menu_item.xml file.
res/menu/menu_item.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/action_settings"
android:orderInCategory="100"
android:title="Household"
app:showAsAction="never"
android:onClick="myHousehold"/>
<item
android:id="#+id/profile"
android:orderInCategory="100"
android:title="About"
app:showAsAction="never"
android:onClick="aboutApp"/>
</menu>
This is the method which uses this XML to set the menu on each activity.
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
You actually don't need the onClick and should add a method like this to enter menu item activities:
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_settings:
{
// Here you can set your intent and start the activity
Intent intent1 = new Intent(this, myActivity.class);
this.startActivityForResult(intent1, MY_ACTIVITY_REQUEST);
return super.onOptionsItemSelected(item);
}
case R.id.profile:
{
// Here you can set your intent and start the activity
return super.onOptionsItemSelected(item);
}
default:
return super.onOptionsItemSelected(item);
}
}
You have to overrideonOptionsItemSelected method from your Activity class and check selected item and do your operation as per your needs.
Try this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_action_settings: {
// Do something
return true;
}
case R.id.profile: {
// Do something
return true;
}
}
return super.onOptionsItemSelected(item);
}
Create a common class like below:
//Utils.java
public class Utils{
Context mContext;
// constructor
public Utils(Context context){
this.mContext = context;
}
public String getUserName(){
return "test";
}
public void doSomething(){
// Do something
}
}
Use it from all activities:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_action_settings: {
Utils utils = new Utils(getApplicationContext());
String username = utils.getUserName();
return true;
}
case R.id.profile: {
// Do something
Utils utils = new Utils(getApplicationContext());
utils.doSomething();
return true;
}
}
return super.onOptionsItemSelected(item);
}
Hope this will help~
I'm having a popup menu on click of action bar button. When i click on the action bar button I'm getting my popup window. But i want to open another activities on clicking the popup menu items. How could i do that?
Following are my code snippets.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#SuppressLint("NewApi") #Override
public boolean onOptionsItemSelected(MenuItem item) {
View menuItemView = findViewById(R.id.action_button);
PopupMenu popupMenu = new PopupMenu(this, menuItemView);
popupMenu.inflate(R.menu.popup);
popupMenu.show();
return true;
}
and my popup menu is as follows,
<menu xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<item
android:id="#+id/one"
android:title="About"
android:visible="true"
android:showAsAction="ifRoom|withText"/>
<item
android:id="#+id/two"
android:title="Contact Us"
android:visible="true"
android:showAsAction="ifRoom|withText"/>
</menu>
What i want to do is, when i click on these menu items another activities has to be opened. How could i do that?
Can someone help me please. Thanks in advance.
Use the id to launch the activity using switch statement with menu itemId
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.one:
Intent intent1 =new Intent(this,ActivityOne.class);//firstActivity
startActivity(intent1);
return true;
case R.id.two:
Intent intent2 =new Intent(this,ActivityTwo.class);//second Activity
startActivity(intent2);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Try this
popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(),
item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
To open activity on popup menu click:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_item1:
Intent intent = new Intent(this, ActivityForItemOne.class);
this.startActivity(intent);
break;
case R.id.menu_item2:
// another startActivity, this is for item with id "menu_item2"
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
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);
}
I'm trying to create an android context menu (the one that pops-up when you press the 'menu' button'). I've read all the tutorials I could find and nothing helped. I'm new to android developing.
I've created the menu.xml file but I don't understand how to give functionality to ID's. This is how my code looks:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#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);
}
}
The thing that I don't get: what to do with 'newGame();' and 'showHelp();'. I wish that when I click on a menu button a new activity starts. How do I do it?
First thing is you have code is for option menu not for context menu
you can call new activity like below
You can directly call a new activity without using option menu by
Intent myIntent = new Intent(this, NewGame.class);
startActivity(myIntent);
if you want to give option to user on press menu button then try below code
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "New Game");
menu.add(0, 1, 1, "Help");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getTitle().toString.equalsIgnoreCase("New Game")) {
Intent intent = new Intent(this, NewGame.class);
startActivity(intent);
finish();
}
else if(item.getTitle().toString.equalsIgnoreCase("Help")) {
Toast.makeText(getBaseContext(), "Help", 2000).show();
}
}
Intent intent = new Intent(this, NewGame.class);
startActivity(intent);
Have you read about how activity works?
This starts the activity NewGame
Intent myIntent = new Intent(this, NewGame.class);
startActivity(myIntent);
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