how to show menu item under overflow icon in android api 8+ - android

How I can force menu item to show under overflow icon. I am providing app support from api level 8 and above. for now it is showing as actionview .
My menuLayout is as follows.
//main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >
<item
android:id="#+id/action_menu_setting"
android:title="#string/menuItemSetting"
app:showAsAction="ifRoom"/>
<item
android:id="#+id/action_signout"
android:title="#string/menuItemLogout"
app:showAsAction="ifRoom"/>
</menu>
in Java class
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
I have tried with other options of showAsAction but none of them worked. Please suggest me how I can show above two menu itme under overflow icon(when i click on over these two will appearer as actionlist.)

layout for custom action bar
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="#drawable/header"
android:orientation="vertical" >
<TextView
android:id="#+id/tvActionBarTitle"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:gravity="center"
android:textColor="#FFFFFF"
android:textSize="30sp" />
<Button.../>
<!-- your code for button -->
</LinearLayout>
You can call below function in onCreate and define button in this function as I have defined appName text view and its OnClick event
private void createCutomActionBarTitle()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
this.getActionBar().setHomeButtonEnabled(true);
}
this.getActionBar().setDisplayShowCustomEnabled(true);
this.getActionBar().setDisplayShowTitleEnabled(false);
this.getActionBar().setBackgroundDrawable(drawable);
this.getActionBar().setIcon(logo);
LayoutInflater inflator = LayoutInflater.from(this);
View v = inflator.inflate(R.layout.custom_action_bar, null);
((TextView) v.findViewById(R.id.tvActionBarTitle)).setText(Global.ACTIVITY_NAME);
this.getActionBar().setCustomView(v);
}
Hope this will be useful for you :)
But clicking physical button of device will not trigger this button you have to look for it, as I don't have any idea about it

Could you post java code ? Do you have code below in your activity ?
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.menu, menu);;
return super.onCreateOptionsMenu(menu);
}
Edit :
I alway use code like this(when i click action_settings it will show action list contains setting and bar, i think just replace android:title="#string/action_settings" with android:icon)
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:showAsAction="always"
android:title="#string/action_settings">
<menu>
<item
android:enabled="true"
android:visible="true"
android:title="setting"
android:id="#+id/setting">
</item>
<item
android:enabled="true"
android:visible="true"
android:title="B"
android:id="#+id/bar">
</item>
</menu>
</item>
<item
android:id="#+id/action_settings1"
android:orderInCategory="100"
android:showAsAction="always"
android:title="#string/action_settings"/>
</menu>
Hope it helps

Related

How to show menu item in action bar?

I want the menu items to show on action bar. There is a lot of space on the ActionBar, but still they don't show up. Every item shown as three dots, why?
.java file
public class GalleryActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery_layout);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
}
.xml file
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:MissionAndroid="http://schemas.android.com/tools">
<item
android:id="#+id/facebookId"
android:title="facebook"
android:icon="#drawable/facebook"
MissionAndroid:showAsAction="always"/>
<item
android:id="#+id/shareId"
android:title="share"
android:icon="#drawable/share"
MissionAndroid:showAsAction="always"/>
<item
android:id="#+id/delete"
android:title="delete"
android:icon="#drawable/delete"
MissionAndroid:showAsAction="always"/>
<item
android:id="#+id/searchId"
android:title="search"
android:icon="#drawable/search"
MissionAndroid:showAsAction="ifRoom"/>
</menu>
Currently, you're using "http://schemas.android.com/tools" which does not offer the functionality you're looking for and your showAsAction modifiers are being ignored.
Try updating your main_menu.xml with the following:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:MissionAndroid="http://schemas.android.com/apk/res-auto">
...
</menu>
Better yet, to follow convention, replace MissionAndroid in this file with app:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/facebookId"
android:title="facebook"
android:icon="#drawable/facebook"
app:showAsAction="always"/>
...
</menu>

Finding view of an icon in overflow menu

I am trying to findview of an overflow icon. After clicking and opening the overflow icon, I tried using in onoptionsitemselected:
View view = getActivity().findViewById(R.id.menu_tag); // null
View view = getActivity().findViewById(R.id.mainMenu); // not null.
<?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/mainMenu"
android:title="#string/text"
android:orderInCategory="101"
android:icon="#drawable/ic_more_vert_white_24dp"
app:showAsAction="always">
<menu>
<item
android:id="#+id/menu_tag"
android:icon="#drawable/tag_32"
app:showAsAction="always|withText"
android:title="#string/tags"/>
<item
android:id="#+id/menu_profile"
android:icon="#drawable/user_32"
app:showAsAction="always|withText"
android:title="#string/profile"/>
<item
android:id="#+id/menu_debug"
android:icon="#drawable/insect_32"
app:showAsAction="always|withText"
android:title="#string/debug"/>
</menu>
</item>
</menu>
It is giving me null but working fine for actionbar items.
You should try to find view in onCreateOptionsMenu method like this :
#Override
public boolean onCreateOptionsMenu(Menu menu) {
this.optionsMenu = menu;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menufile, menu);
MenuItem item = menu.findItem(R.id.mainmenu);
return true;
}
I found a solution by setting actionview to imagebutton and then finding the view.

Menu icon is not displaying in action bar

I need to inflate custom menu in Fragment.
I have only one menu item.But the icon is not displaying.
Can someone tell what is wrong with my code
My menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" >
<item
android:id="#+id/search"
android:icon="#android:drawable/ic_search_category_default"
app:showAsAction="always"
android:title="Search"/></menu>
And I set in onCreateView()
setHasOptionsMenu(true);
getActivity().invalidateOptionsMenu();
And inflating the menu
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.menu, menu);
}
Resulting screen attached below. I need to have the search icon instead of the menu overflow icon.
I know I'm a little late for the party, but hope I can help someone else. Today I was facing this SAME problem.
I fixed using android:showAsAction="always" instead of app:showAsAction="always"
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/bluetooth_status_off"
android:orderInCategory="0"
android:icon="#drawable/bluetooth_red"
android:title="#string/app_name"
android:showAsAction="always" />
</menu>
on the showAsAction is underlined with red (warning), but works fine.
I Think You should use
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" >
<item
android:id="#+id/search"
android:icon="#drawable/ic_search_category_default"
app:showAsAction="always"
android:title="Search"/></menu>
and
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mymenu, menu);
return true;
}
Sorry to late but put this code in your onCreate()
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
You have to add the following property app:showAsAction="ifRoom"
Make sure, you've added a menu item without an icon.
Example:
<?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/next_btn"
android:checked="true"
android:icon="#android:drawable/ic_input_add"
android:title="Item"
app:showAsAction="ifRoom" />
<item
android:id="#+id/action_settings"
android:title="Settings" />
</menu>
Thanks to action_settings, it'll automatically add an overflow icon.
make a menu with the code below...
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="#string/action_settings"/>
<item
android:id="#+id/action_search"
android:title="Search"
android:icon="#android:drawable/ic_menu_search"
android:showAsAction="always"
android:actionViewClass="android.widget.SearchView" />
</menu>
and set it as your menu..
This is default behaviour of the Overflow menu from the ActionBar.
If you want to show the Icons in the overflow menu, override the onMenuOpened method in your activity with this code snippit:
#Override
public boolean onMenuOpened(int featureId, Menu menu) {
if(featureId == Window.FEATURE_ACTION_BAR && menu != null){
if(menu.getClass().getSimpleName().equals("MenuBuilder")){
try{
Method m = menu.getClass().getDeclaredMethod(
"setOptionalIconsVisible", Boolean.TYPE);
m.setAccessible(true);
m.invoke(menu, true);
}
catch(NoSuchMethodException e){
Log.e("MyActivity", "onMenuOpened", e);
}
catch(Exception e){
throw new RuntimeException(e);
}
}
}
return super.onMenuOpened(featureId, menu);
}
If you're running your code on Android 3.0+, the icons in the menu are not shown by design.
This is a design decision by Google.
You can read more about this on Android developers blog.
Copy your menu xml code.
Delete your menu file
Now create a new menu file in res->menu directory
And name it with different name
Now Run

How to change Custom Font of Android Menu Item?

I have the following Android Java and XML code. I want to change the font of Menu Items of my app. I know only that we can change the font of TextView using setTypeface but not able to find anyway for Menu Item.
JAVA Code-:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh1:
Toast.makeText(this, "Item1 Selected", Toast.LENGTH_SHORT)
.show();
break;
case R.id.action_refresh2:
Toast.makeText(this, "Item2 Selected", Toast.LENGTH_SHORT)
.show();
break;
default:
break;
}
}
XML Code-:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/action_refresh1"
android:orderInCategory="100"
android:showAsAction="always"
android:title="Item1"/>
<item
android:id="#+id/action_refresh2"
android:orderInCategory="100"
android:showAsAction="always"
android:title="Item2"/>
</menu>
I want to change the font of two menu item , but don't know how to integrate settypface for Menu Item.
Create Style in styles.xml
<style name="Style_TextView">
<item name="fontFamily">#font/myriadproregular</item>
</style>
Add Below code into android.support.design.widget.NavigationView
app:itemTextAppearance="#style/Style_TextView"
Note: It works for android.support.design.widget.NavigationView
you have to provide a custom layout for the menu item.
First, in your menu XML set one of the following
CASE 1 if you are using the support library:
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_save"
android:title="#string/action_save"
android:icon="#drawable/ic_action_save"
android:orderInCategory="100"
app:showAsAction="always"
app:actionLayout="#layout/layout_menu_save"/>
</menu>
CASE 2 if you are not using the support library:
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/action_save"
android:title="#string/action_save"
android:icon="#drawable/ic_action_save"
android:orderInCategory="100"
android:showAsAction="always"
android:actionLayout="#layout/layout_menu_save"/>
</menu>
Then in the actionLayout (layout_menu_save.xml in my example) write the following:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#drawable/background_transparent_stateful">
<com.example.YourCustomTypefaceTextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:gravity="center_vertical"
android:text="#string/action_save"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:gravity="center_vertical"
android:src="#drawable/ic_action_save"
android:contentDescription="#string/action_save"/>
</LinearLayout>
The background drawable (background_transparent_stateful) is useful for having touch feedback on your custom layout:
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true"
android:drawable="#20FFFFFF">
</item>
<item
android:drawable="#android:color/transparent">
</item>
</selector>
This way you will have a text with custom font on the left as a label with an icon on the right.
Obviously you can customize the layout as you prefer!
EDIT:
If you are using the support library and your activity Theme extends the AppCompatTheme you can get the typical Lollipop "ripple effect" for a better looking touch feedback.
Just replace the custom background with:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackgroundBorderless">
...
</LinearLayout>
Just add the font of your choice to your base application theme. Note that that makes the selected font the base font for any unspecified font attributes.
<item name="android:fontFamily">#font/your_font</item>
XML
<?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_edit"
android:title="#string/edit"
android:visible="true"
app:showAsAction="always" />
</menu>
IN ACTIVITY OR IN FRAGMENT
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
Typeface face = Typeface.createFromAsset(getActivity().getAssets(),"fonts/OpenSans-Regular.ttf"); // THIS
TypefaceSpan face = new TypefaceSpan("<REPLACE_WITH_FONT_NAME>"); // OR THIS
SpannableStringBuilder title = new SpannableStringBuilder(getContext().getString(R.string.edit));
title.setSpan(face, 0, title.length(), 0);
menu.add(Menu.NONE, R.id.action_edit, 0, title); // THIS
MenuItem menuItem = menu.findItem(R.id.action_edit); // OR THIS
menuItem.setTitle(title);
super.onCreateOptionsMenu(menu, inflater);
}
You can also use a SpannableStringBuilder when you add a menu item with a TypefaceSpan. For each menu item do something like
TypefaceSpan span = new TypefaceSpan("<REPLACE_WITH_FONT_NAME>");
SpannableStringBuilder title = new SpannableStringBuilder("My Menu Item Title");
title.setSpan(span, 0, title.length(), 0);
menu.add(Menu.NONE, id, index, title);
If your app only needs to work on Android Pie (API level 28) and above you can construct a TypefaceSpan from a Typeface in onPrepareOptionsMenu. Otherwise you can use a CustomTypefaceSpan class like this answer suggests:
public boolean onPrepareOptionsMenu(Menu menu) {
int customFontId = R.font.metropolis_medium;
for (int i = 0; i < menu.size(); i++) {
MenuItem menuItem = menu.getItem(i);
String menuTitle = menuItem.getTitle().toString();
Typeface typeface = ResourcesCompat.getFont(this, customFontId);
SpannableString spannableString = new SpannableString(menuTitle);
// For demonstration purposes only, if you need to support < API 28 just use the CustomTypefaceSpan class only.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
TypefaceSpan typefaceSpan = typeface != null ?
new TypefaceSpan(typeface) :
new TypefaceSpan("sans-serif");
spannableString.setSpan(typefaceSpan, 0, menuTitle.length(),
Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
} else {
CustomTypefaceSpan customTypefaceSpan = typeface != null ?
new CustomTypefaceSpan(typeface) :
new CustomTypefaceSpan(Typeface.defaultFromStyle(Typeface.NORMAL));
spannableString.setSpan(customTypefaceSpan, 0, menuTitle.length(),
Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
}
menuItem.setTitle(spannableString);
}
return true;
}
main.menu.xml:
<?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/settings"
android:onClick="openSettings"
android:title="#string/settings"
app:showAsAction="never" />
<item
android:id="#+id/about"
android:onClick="openAbout"
android:title="#string/about"
app:showAsAction="never" />
</menu>
Before & After:
I found this solution is usefull for me .hope it will help full new surfers.
your menu main.xml
<?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/item1"
android:title="User"
android:orderInCategory="100"
android:visible="true"
app:showAsAction="always"
app:actionViewClass="android.widget.Button"
/>
</menu>
After you inflated the custom menu, you can make a reference to the item of the menu. When you obtain the reference to the menu item, you will be able to customize the item to show icon and Unicode text. Your icon image file has to be stored in the
res/drawable folder.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
//reference to the item of the menu
MenuItem i=menu.findItem(R.id.item1);
Button button_menu =(Button) i.getActionView();
if(itemuser!=null){
// Create Typeface object to use unicode font in assets folder
Typeface font= Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/arial.ttf");
// Set unicode font to menu item
button_menu .setTypeface(font);
// Set item text and color
button_menu .setText(getResources().getString(R.string._text));
button_menu .setTextColor(Color.WHITE);
// Make item background transparent
button_menu .setBackgroundColor(Color.TRANSPARENT);
// Show icon next to the text
Drawable icon=getApplicationContext().getResources().getDrawable( R.drawable.user);
button_menu .setCompoundDrawablesWithIntrinsicBounds( icon, null, null, null );
}
return true;
}
Simply set itemTextAppearance property of the NavigationView to system or custom style:
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main_navigation"
app:itemBackground="#color/white"
app:itemTextAppearance="#style/TextAppearance.AppCompat"
app:itemTextColor="#color/saintpatrickblue"
app:menu="#menu/activity_main_navigation_drawer"/>
The answer by #brahmyadigopula works well.
Here is just a more complete version for the sake of simplification:
The Menu
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<item
android:id="#+id/update"
android:showAsAction="always"
android:title="#string/menu_update"
tools:ignore="UnusedAttribute"
android:actionViewClass="android.widget.Button"/>
</menu>
In your Activity or Fragment:
// Inflater the menu based on the layout above
inflater.inflate(menuRes, menu);
// Set font type face
if (setCustomFontType){
final MenuItem menuItem = menu.findItem(R.id.update);
String title = menuItem.getTitle().toString();
Button button_menu = (Button) menuItem.getActionView();
button_menu.setTypeface("<REPLACE_WITH_FONT_NAME>");
button_menu.setText(title);
button_menu.setTextColor(Color.WHITE);
button_menu.setBackgroundColor(_getResources().getColor(R.color.transparent_color));
button_menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onOptionsItemSelected(menuItem);
}
});
}
super.onCreateOptionsMenu(menu, inflater);
If you are using android.support.design library then:
In theme:
app:itemTextAppearance="#style/bottom_navigation_textappreance"
if you are using Material design then:
In XML:
app:itemTextAppearanceActive="#style/bottom_navigation_textappreance"
app:itemTextAppearanceInactive="#style/bottom_navigation_textappreance"
In theme:
<style name="bottom_navigation_textappreance" parent="Widget.Design.BottomNavigationView">
<item name="fontFamily">#font/fira_sans_bold</item>
</style>

Android adding a submenu to a menuItem, where is addSubMenu()?

I want to add a submenu inside my OptionsMenu to a menuItem, programatically according to my parameters. I've checked "MenuItem" in android sdk and there is no addSubMenu() method!, although you can find "hasSubMenu()" and "getSubMenu".
Was thinking on doing this in onCreateOptionsMenu:
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem mi = menu.getItem(MYITEMID); // << this is defined in my XML optionsMenu
SubMenu subm = mi.addSubMenu(0,1,0,"Map 1"); // no addSubMenu() method!!!???
....
How do I create a submenu inside a menuitem in code?
Sometimes Android weirdness is really amazing (and amusing..). I solved it this way:
a) Define in XML a submenu placeholder like this:
<item android:visible="true" android:id="#+id/m_area"
android:titleCondensed="Areas"
android:title="Areas"
android:icon="#drawable/restaur"
android:enabled="true">
<menu>
<item android:id="#+id/item1" android:title="Placeholder"></item>
</menu>
</item>
b) Get sub menu item in OnCreateOptionsMenu, clear it and add my submenu items, like this:
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mapoptions, menu);
int idx=0;
SubMenu subm = menu.getItem(MYITEM_INDEX).getSubMenu(); // get my MenuItem with placeholder submenu
subm.clear(); // delete place holder
while(true)
{
anarea = m_areas.GetArea(idx); // get a new area, return null if no more areas
if(anarea == null)
break;
subm.add(0, SUBAREASID+idx, idx, anarea.GetName()); // id is idx+ my constant
++idx;
}
}
I know this is an old question, but I just came across this problem myself.
The most straightforward way of doing this, seems to be to simply specify the item itself as a submenu, then add to this item.
E.g.:
menu.add(groupId, MENU_VIEW, Menu.NONE, getText(R.string.menu_view));
menu.add(groupId, MENU_EDIT, Menu.NONE, getText(R.string.menu_edit));
SubMenu sub=menu.addSubMenu(groupId, MENU_SORT, Menu.NONE, getText(R.string.menu_sort));
sub.add(groupId, MENU_SORT_BY_NAME, Menu.NONE, getText(R.string.menu_sort_by_name));
sub.add(groupId, MENU_SORT_BY_ADDRESS, Menu.NONE, getText(R.string.menu_sort_by_address));
:
:
Here's a complete answer which builds on the idea of using a placeholder but uses mostly xml to add the submenu.
If you have a menu like so called main_menu.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="My Menu"
android:id="#+id/my_menu_item">
<!-- A empty SubMenu -->
<menu></menu>
</item>
</menu>
Create another menu sub_menu.xml which will be used in my_menu_item:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="SubMenu One"
android:id="#+id/submenu_one" />
<item android:title="SubMenu Two"
android:id="#+id/submenu_two" />
<item android:title="SubMenu Three"
android:id="#+id/submenu_three" />
</menu>
In your onCreateOptionsMenu:
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate your main_menu into the menu
getMenuInflater().inflate(R.menu.main_menu, menu);
// Find the menuItem to add your SubMenu
MenuItem myMenuItem = menu.findItem(R.id.my_menu_item);
// Inflating the sub_menu menu this way, will add its menu items
// to the empty SubMenu you created in the xml
getMenuInflater().inflate(R.menu.sub_menu, myMenuItem.getSubMenu());
}
This solution is nice since the inflater handles most of the work.
The best way to do this is in your xml menu file. You can do this by creating a new menu object inside of an item:
<menu>
<item>
...
<menu>
...
</menu>
...
</item>
</menu>
To provide a comprehensive example of Phil's answer, here is my complete, working XML for a menu with two choices, each of which is a menu with three choices. I intend to add a third menu to the top level ...
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:HTMLCode="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/Examine"
android:title="#string/Examine"
HTMLCode:showAsAction="always">
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:HTMLCode="http://schemas.android.com/apk/res-auto" >
<item android:id="#+id/load"
android:title="#string/load"
HTMLCode:showAsAction="ifRoom|withText" />
<item android:id="#+id/findfirst"
android:title="#string/findfirst"
HTMLCode:showAsAction="ifRoom|withText" />
<item android:id="#+id/findnext"
android:title="#string/FindNext"
HTMLCode:showAsAction="ifRoom|withText" />
</menu>
</item>
<item android:id="#+id/Redirect"
android:title="#string/Redirect"
HTMLCode:showAsAction="ifRoom|withText">
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:HTMLCode="http://schemas.android.com/apk/res-auto" >
<item android:id="#+id/getRedirect"
android:title="#string/getRedirect"
HTMLCode:showAsAction="ifRoom|withText" />
<item android:id="#+id/toggleRedirect"
android:title="#string/toggleRedirect"
HTMLCode:showAsAction="ifRoom|withText" />
<item android:id="#+id/copyRedirect"
android:title="#string/copyRedirect"
HTMLCode:showAsAction="ifRoom|withText" />
</menu>
</item>
</menu>
You should consider use a ActionProvider instead.
public class MyActionProvider extends ActionProvider {
private Context mContext;
public MyActionProvider(Context context) {
super(context);
mContext = context;
}
#Override
public View onCreateActionView() {
//LayoutInflater layoutInflater = LayoutInflater.from(mContext);
return null;
}
#Override
public void onPrepareSubMenu(SubMenu subMenu) {
super.onPrepareSubMenu(subMenu);
subMenu.clear();
subMenu.add("menu 1");
subMenu.add("menu 2");
subMenu.add("menu 3");
}
#Override
public boolean hasSubMenu() {
return true;
}
#Override
public boolean onPerformDefaultAction() {
return super.onPerformDefaultAction();
}
}
I would just create the submenu in xml file, and in run time get the submenu from menu object, (using findItem(id) method) and use submenu.setVisible(boolean) to add/remove it on run time.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/menu1" android:alphabeticShortcut="a"
android:title="Menu No. 1" android:orderInCategory="1" />
<item android:id="#+id/menu2" android:alphabeticShortcut="b"
android:title="Menu No. 2" android:orderInCategory="2">
<menu >
<group android:id="#+id/group2" android:checkableBehavior="single">
<item android:id="#+id/submenu1" android:title="SubMenu No. 1" />
<item android:id="#+id/submenu2" android:title="SubMenu No. 2" />
</group>
</menu>
</item>

Categories

Resources