How to Add a CheckBox in Toolbar with custom background - android - android

Hi i'm new in android and here
i want to Have a CheckBox in my Toolbar with a custom background
my use case is : i want to add current post(in my activity) to favorites list by a checkbox in toolbar
and i wanna use a star(on/off) icon.
i tried this but the checkBox is null
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/shwo_menu_download_mp3"
android:title="#string/download_mp3"
app:showAsAction="never"/>
<item android:id="#+id/show_menu_add_to_fav"
android:checked="true"
android:enabled="true"
app:showAsAction="always"
/>
<item android:id="#+id/show_menu_setting"
android:title="#string/show_menu_setting"
app:showAsAction="never" />
and my Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_speech);
initCheckBox();
...
}
CheckBox checkBoxFav;
private void initCheckBox() {
checkBoxFav = (CheckBox) findViewById(R.id.show_menu_add_to_fav);
checkBoxFav.setText("some Text");
}

with toolbar you can do this
setSupportActionBar(toolbar);
View view= getLayoutInflater().inflate(R.layout.view_, null);
Checkbox chbox = view.findViewById(..);
//chbox.do what u want with it
toolbar.addView(logo);
the view layout contains a checkbox and design it as you wish

You have to follow these steps:
1. Create a toolbar and add it to your activity. I'm not going to explain that since there are a ton of tutorials on the matter.
2. Create a menu with a checkbox widget in it:
<?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_star"
android:checkable="true"
app:actionViewClass="android.widget.CheckBox"
app:showAsAction="ifRoom"
android:title="#string/favorite" />
</menu>
Add the set of icons in the drawable folder. One icon for the unchecked state and one icon for the checked state.
Create a resource file and name it whatever you want (In this example the name is star.xml), add it to the drawable folder and insert the following code in it:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="true"
android:drawable="#drawable/star_black"
/>
<item
android:state_selected="true"
android:drawable="#drawable/star_black"
/>
<item
android:state_checked="false"
android:drawable="#drawable/star_border_black"
/>
<item
android:drawable="#drawable/star_border_black"
/>
</selector>
create an onCreateOptionsMenu method in your activity and insert the following code. The icon of the checkbox will change automatically after getting checked or unchecked.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu,menu);
CheckBox checkBox = (CheckBox)menu.findItem(R.id.menu_star).getActionView();
checkBox.setButtonDrawable(R.drawable.star);//set the icon to star.xml
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//set the action of the checkbox
}
});
return super.onCreateOptionsMenu(menu);
}

Related

Adding long press to dynamically generated menu items

Okay, so I have a dynamic menu (In my navigation drawer), generated like so:
In my Main.java onCreate():
DatabaseManager databaseAccess = DatabaseManager.getInstance(this);
databaseAccess.open();
List<String> folders = databaseAccess.getFolders();
databaseAccess.close();
// Set up the menu items
setupMenu(folders);
This gets the headings into an array called 'folders', then runs the setupMenu function:
private void setupMenu(List<String> folders) {
// Sets up the menu
Log.i("Folder Size",String.valueOf(folders.size()));
NavigationView navView = findViewById(R.id.nav_view);
Menu menu = navView.getMenu();
int x = 0;
while(x < folders.size()) {
menu.add(R.id.myfolders,Menu.NONE,Menu.NONE,folders.get(x++));
}
navView.invalidate();
}
Which adds it to the id:myfolders in activity_main_drawer:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<item android:title="My Folders"
android:orderInCategory="1"
android:id="#+id/myfolders">
<menu></menu>
</item>
<item android:checkableBehavior="single" android:orderInCategory="2">
<menu android:id="#+id/about_menu">
<item android:id="#+id/system_about"
android:title="About"
android:icon="#drawable/ic_info" />
</menu>
</item>
</menu>
This all works perfectly, however I want to add longpress functionality to my menu items. I have no idea how to go about doing this, can anyone help?
You get a MenuItem from menu.add() then you can call:
menuItem.getActionView().setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return false; // true
}
});
But not before you set action view: menuItem.setActionView(new ImageButton(this)).

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>

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

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

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