how to go to main menu on click on submenu? - android

how to go to main menu onclick on sub menu in android. i am trying this but unable to do that.
this is java
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
sub = menu.getItem(0).getSubMenu();
sub.setHeaderTitle("sub menu...");
sub.setHeaderIcon(R.drawable.ic_voice);
//Toast.makeText(this, "submenu label=", Toast.LENGTH_SHORT).show();
MenuItem item = menu.findItem(R.id.action_settings);
TextView iv= (TextView) item.getActionView().findViewById(R.id.action_settings);
sub.getItem(0).setActionView(iv);
Toast.makeText(this, "before onclick listener=", Toast.LENGTH_SHORT).show();
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "-submenu header title clicked", Toast.LENGTH_SHORT).show();
}
});
return super.onPrepareOptionsMenu(menu);
}
this is 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/action_refresh"
android:orderInCategory="100"
android:title="Refresh" />
<item
android:id="#+id/action_settings"
android:icon="#drawable/ic_voice"
android:title="Settings"
app:actionViewClass="android.widget.TextView">
<menu>
<item
android:id="#+id/change_password"
android:title="change password" />
<item
android:id="#+id/user_details"
android:title="user details" />
</menu>
</item>
</menu>
code
showing is submenu when we click on submenu text it should go back to mainmenu

Android doesn't provide some mechanism to set onClickListener to SubMenu header, but you can use a hack.
First of all, get rid of SubMenu header:
SubMenu sub = menu.findItem(R.id.action_settings).getSubMenu();
sub.clearHeader();
It's not secure to use getItem(0), because the order of your items may change, so I used findItem(R.id.action_settings) instead.
Next, you should add one more item to your SubMenu:
<menu>
<item
android:id="#+id/sub_title"
android:title="sub menu..."/>
<item
android:id="#+id/change_password"
android:title="change password" />
<item
android:id="#+id/user_details"
android:title="user details" />
</menu>
But now all three items will looks the same, so you need to change color of first MenuItem
MenuItem headItem = sub.findItem(R.id.sub_title);
SpannableString s = new SpannableString(headItem.getTitle());
s.setSpan(new ForegroundColorSpan(Color.GRAY), 0, s.length(), 0);
headItem.setTitle(s);
Also, don't use onPrepareOptionsMenu() for that purposes, because it calls every time when you open menu, you can put all that code inside onCreateOptionsMenu():
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
SubMenu sub = menu.findItem(R.id.action_settings).getSubMenu();
sub.clearHeader();
MenuItem headItem = sub.findItem(R.id.sub_title);
SpannableString s = new SpannableString(headItem.getTitle());
s.setSpan(new ForegroundColorSpan(Color.GRAY), 0, s.length(), 0);
headItem.setTitle(s);
return true;
}
And the last step - listen to clicks on that MenuItem:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.sub_title:
Toast.makeText(this, "-submenu header title clicked", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}

Related

NavigationView menu's .add not working except in main bodies of onCreate() and onResume()

This is the code of onNavigationItemSelcted
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Menu eventMenu = mNavigationView.getMenu();
eventMenu.add(R.id.events,Menu.NONE,1,"newEvent").setIcon(R.drawable.hangouts_white);
// extra code
}
However, I can perfectly use this add method in onCreate() and onResume(). But, again, if I use this method in onClick() in onCreate() or onResume(), it does not work. As long as it is in their main body, it will work.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNavigationView = findViewById(R.id.navigation_view);
drawerAndToggle();//For drawerlayout setup
Menu eventMenu = mNavigationView.getMenu();
MenuItem eventItem = eventMenu.findItem(R.id.add_custom_event);
eventItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
// This gets executed but does not do anything
eventMenu.add(R.id.events,Menu.NONE,1,"New item");
return true;
}
});
// This one works fine
eventMenu.add(R.id.events,Menu.NONE,1,"New item");
}
But I need to add an item if the user selects "Add Item" which is one of the menu items in the Navigation Drawer. What am I missing or what should I be adding?
Here is my nav_menu XML of my navigation view
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<group android:id="#+id/events">
<item
android:orderInCategory="1"
android:id="#+id/item1"
android:title="Item 1" />
<item
android:orderInCategory="1"
android:id="#+id/item2"
android:title="Item 2" />
</group>
<group android:id="#+id/settings">
<item
android:orderInCategory="2"
android:id="#+id/add_item"
android:title="Add Item"/>
</group>
</menu>

Android How to open the options menu item after clicking a button?

I'm using menu items like this.
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu_overflow"
android:enabled="true"
android:icon="#drawable/ic_menu_moreoverflow_mtrl_alpha"
android:title=""
app:showAsAction="ifRoom">
<menu>
<item
android:id="#+id/action_city"
android:icon="#drawable/ic_change_city"
android:title="Change City"
app:showAsAction="never" />
<item
android:id="#+id/action_language"
android:icon="#drawable/ic_change_language"
android:title="Change Language"
app:showAsAction="never" />
<item
android:id="#+id/action_change_theme"
android:icon="#drawable/ic_change_theme"
android:title="Change Theme"
app:showAsAction="never" />
</menu>
</item>
</menu>
Now How can I expand Menu Item -> menu_overflow programmatically after clicking a button?
My code is:
activity.openOptionsMenu();
---------
toolbar.showOverflowMenu();
---------
menu_overflow.expandActionView();
---------
menu_overflow.getSubMenu().getItem().expandActionView();
But those above codes are not working.
Here is design how it looks like.
Create one xml file names as menu_main. 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"
tools:context="example.javatpoint.com.optionmenu.MainActivity">
<item android:id="#+id/item1"
android:title="Item 1"
android:icon="#drawable/ic_action_accept" />
<item android:id="#+id/item2"
android:title="Item 2"/>
<item android:id="#+id/item3"
android:title="Item 3"
app:showAsAction="withText"/>
</menu>
Then add these code in your Activity :
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.item1:
Toast.makeText(getApplicationContext(),"Item
Selected",Toast.LENGTH_LONG).show();
return true;
case R.id.item2:
Toast.makeText(getApplicationContext(),"Item 2
Selected",Toast.LENGTH_LONG).show();
return true;
case R.id.item3:
Toast.makeText(getApplicationContext(),"Item 3
Selected",Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Try this
YourActivity.this.openOptionsMenu();
Use Activity.openOptionsMenu(), but you may need to post delay to call it. like below
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
openOptionsMenu();
}
}, 1000);
If you need to automatically show sub menu. you can call menu.performIdentifierAction after openOptionsMenu, like below
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
openOptionsMenu();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mainMenu.performIdentifierAction(R.id.submenu, 0);
}
}, 500);
}
}, 1000);
Android Dev efficiency tools: https://play.google.com/store/apps/details?id=cn.trinea.android.developertools
Android Open Source Projects: https://p.codekk.com/

How to add a line between items in a menu application title bar in Android Studio?

I have a menu in the title bar of my Android app, that is not a pop-up Menu. In it I have some items. I want to add a line, or a separator, between just one pair of items in the list. I don't want dividers between all the items, just one pair. I tryed with groups who have different IDs, not worked, also tryed with android:actionlayout, no succes.
My current menu looks like this in design mode. I want to do something like this.
My XML containing my 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:title="#string/editare_nume_jucatori">
<!-- submeniul meu -->
<menu>
<item
android:id="#+id/M_Jucator1"
android:enabled="true"
android:title="#string/Jucatorul1" />
<item
android:id="#+id/M_Jucator2"
android:enabled="true"
android:title="#string/Jucatorul2" />
</menu>
</item>
<item
android:id="#+id/M_Detalii"
android:icon="#drawable/dice10"
android:title="#string/detalii_text_meniu" />
<item
android:id="#+id/M_Despre_Aplicatie"
android:icon="#drawable/dice10"
android:title="#string/despre_aplicatie" />
<item
android:id="#+id/M_Iesire_Aplicatie"
android:icon="#drawable/m3"
android:title="#string/IesireAplicatie" />
</menu>
My Java code for the menu:
Menu meniu1; //a variable used in my menu
//to show my menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.meniul_meu, menu);
meniu1 = menu; //this is my variable from up declaration
return true;
}
//here execute different actions for items clicked in menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
//click on my item ID from menu and execute
case R.id.M_Jucator1:
...(code code)...
return true;
//click on my item ID from menu and execute
case R.id.M_Jucator2:
..(code code)...
return true;
//click on my item ID from menu and execute
case R.id.M_Detalii:
..(code code)...
return true;
//cand dai click pe iesire din meniu
case R.id.M_Iesire_Aplicatie:
..(code code)..
return true;
default:
return super.onOptionsItemSelected(item);
}
} //finish meniu codes
Group your items in the XML menu, such as:
......
<group>
<items...
</group>
<group>
<items...
</group>
.....
And the in your code use:
final Menu menu = ((Toolbar)this.findViewById(R.id.your_toolbar)).getMenu();
MenuCompat.setGroupDividerEnabled(menu, true);

Android actionbar submenu items displayed on top of the actionbar instead of below the bar

I need to show the submenu below the bar, not on top of the bar itself.
Copying my actionbar xml below
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
<item
android:id="#+id/action_pages"
android:orderInCategory="1"
android:showAsAction="withText|always"
android:icon="#drawable/ic_action_pages"
android:title="">
<menu>
<item android:id="#+id/item1" android:title="Placeholder"></item>
</menu>
</item>
</menu>
In the activity (App also has a navigation drawer)
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
Simply.
<style name="AppTheme" parent="AppBaseTheme">
<item name="actionOverflowMenuStyle">#style/OverflowMenu</item>
</style>
<style name="OverflowMenu" parent="Widget.AppCompat.PopupMenu.Overflow">
<!-- Required for pre-Lollipop. -->
<item name="overlapAnchor">false</item>
<!-- Required for Lollipop. -->
<item name="android:overlapAnchor">false</item>
</style>
Preamble
As usual, I faced a strange problem while developing an Android app, tried to find a solution and landed to this question. As it was in many cases before, there is no an answer. So I was compelled to solve the problem from scratch and now posting the answer with my workaround.
Input
I have an Android app with action bar and some menu items, which have to be extended with dropdown submenu. First attempt was to implement it as suggested by Android documentation. So I added new menu item menu_sort into existing action bar menu and sub-menu container into it:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#+id/id1" android:icon="#drawable/ic_1"
android:title="#string/id1" android:showAsAction="withText|always"/>
...
<item
android:id="#+id/menu_sort"
android:icon="#drawable/ic_menu_sort_selector"
android:title="▾"
android:titleCondensed="▾"
android:showAsAction="withText|always">
<menu>
<item
android:id="#+id/menu_sort_by_name"
android:showAsAction="never"
android:checkable="true"
android:checked="true"
android:title="#string/sort_by_name"/>
<item
android:id="#+id/menu_sort_by_priority"
android:showAsAction="never"
android:checkable="true"
android:checked="false"
android:title="#string/sort_by_priority"/>
<item
android:id="#+id/menu_sort_by_memory"
android:showAsAction="never"
android:checkable="true"
android:checked="false"
android:title="#string/sort_by_memory"/>
</menu>
</item>
</menu>
Result
The effect was exactly as described in the question: the submenu is displayed on top of the action bar. Here is the screenshot taken on Android 5.1.1:
I played with many options and code snippets - nothing helped. Finally I came to the following
Solution
First, move all the submenu into a separate menu layout, say, menu/sorting.xml, and remove it from menu_sort item of the main menu (shown above).
Second, modify or create onPrepareOptionsMenu event handler with the following code:
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
// as solution utilizes PopupMenu,
// take care about older Android versions if necessry
// if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
// here goes most crazy part: we use menu id
// to retrieve corresponding view, automatically created by OS;
// imho, this is a hack, and menu item should have getView() method or similar;
View menuItemView = findViewById(R.id.menu_sort);
// by the way, menuItemView could probably be null under some circumstances
// create a popup anchored to the view (menu item)
final PopupMenu popupMenu = new PopupMenu(this, menuItemView);
// API 14
// popupMenu.inflate(R.menu.sorting);
// API 11 (HONEYCOMB)
popupMenu.getMenuInflater().inflate(R.menu.sorting, popupMenu.getMenu());
// process popup clicks as appropriate
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener()
{
#Override
public boolean onMenuItemClick(MenuItem item)
{
switch(item.getItemId())
{
// ... place some code
}
return true;
}
});
// bind the popup to the item menu
menu.findItem(R.id.menu_sort).setOnMenuItemClickListener(new OnMenuItemClickListener()
{
#Override
public boolean onMenuItemClick(MenuItem item)
{
popupMenu.show();
return true;
}
});
return super.onPrepareOptionsMenu(menu);
}
Here is the result:
Now the dropdown is displayed as expected from very beginning.
#Stan's solution doesn't work for me, so here's my way to implement sub-menu on top of ActionBar (but below the main-menu of course):
I've created 2 xml files: menu_main.xml and menu_more.xml located in res/menu directory
The first one 'menu_main.xml' contain the menu:
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- our addMenu doesn't have sub-items-->
<item
android:id="#+id/action_add"
android:icon="#drawable/ic_note_add_white_24dp"
android:title="#string/action_add"
app:showAsAction="ifRoom"/>
<!-- our moreMenu which show drop-down menu when clicked-->
<item
android:id="#+id/action_more"
android:icon="#drawable/ic_more_vert_white_24dp"
android:title="#string/action_more" <!--in text: "more"-->
app:showAsAction="always"/>
</menu>
And the second one 'menu_more.xml' contain the drop-down menu:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- This menu will be hidden by default-->
<!-- But will be visible when moreMenu with '#+id/action_more' is clicked-->
<item
android:id="#+id/action_settings"
app:showAsAction="ifRoom|withText"
android:title="#string/action_settings" <!-- In text: "Settings"-->
android:visible="true"/>
</menu>
Here is what previous menus look like:
result-after-add-2-xmls (i have not enough 10 reputation to display image)
In the activity, i've overridden this method:
public boolean onPrepareOptionsMenu(Menu menu)
In the previous method, i get reference to the main menuItem (in this case is menu with #+id/action_more located in menu_main.xml file), then set setOnMenuItemClickListener on it and finally, declare and set up a PopupMenu instance to manage and display sub-menu items:
// show popup menu when menuMore clicked
menu.findItem(R.id.action_more).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener()
{
#Override
public boolean onMenuItemClick(MenuItem item)
{
// get reference to menuMore item
View menuMore = findViewById(item.getItemId());
// create a popup anchored to the view (menuMore)
// notes: if declare and set up PopupMenu Outside of this onMenuItemClick()
// then it'll not work!
// Because: the view you put into PopupMenu() could be null
final PopupMenu popupMenu = new PopupMenu(getApplicationContext(), menuMore);
// inflate 'menu_more.xml' layout file
// which contain all sub-items of menu
popupMenu.getMenuInflater().inflate(R.menu.menu_more, popupMenu.getMenu());
// process popup clicks on sub-items
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener()
{
#Override
public boolean onMenuItemClick(MenuItem item)
{
switch(item.getItemId()){
case R.id.action_settings:
Toast.makeText(getApplicationContext(), "showing SettingsActivity..",
Toast.LENGTH_SHORT).show();
break;
// more items go here
}
return true;
}
});
popupMenu.show();
return true;
}
});
return super.onPrepareOptionsMenu(menu);
And here is final result:
final-look-drop-down-menu

Android - ActionBar item - onClickListener

I'm trying to implement onClickListener for the item which is a submenu of the ActionBar. Whatever I'm trying to do the result is the same - "Unfortunatelly, application has stopped." However there are no errors during compilation. All seems to be ok, but it is't. What goes wrong here? Thanks for help.
This is my code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
View view = (View) menu.findItem(R.id.delete).getActionView();
view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Execute when actionbar's item is touched
}
});
return true;
}
And here is the main.xml file where ActionBar and its item is created
<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:id="#+id/delete"
android:title="#string/delete"
android:showAsAction="always"
android:orderInCategory="200"/>
</menu>
</item>
</menu>
getActionView() returns a valid object (not null) only you have a custom action view (with setActionView)

Categories

Resources