Getting menu clicks - android

Alright, this might be simple but I dunno how to do it! I have my menu defined through XML, as shown below. It loads and everything.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/home"
android:title="Home" />
<item android:id="#+id/about"
android:title="About" />
<item android:id="#+id/quit"
android:title="Quit" />
</menu>
Now, going through onOptionsItemSelected(), how do I tell which menu item is selected?
This is from an example... What would the case's be?
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
Toast.makeText(this, "Home", Toast.LENGTH_LONG).show();
return true;
case 2:
Toast.makeText(this, "About", Toast.LENGTH_LONG).show();
return true;
case 3:
Toast.makeText(this, "Quit", Toast.LENGTH_LONG).show();
return true;
}
return false;
}

Your case statements should use the ids defined in your xml:
case R.id.home:
....
case R.id.about:
....
case R.id.quit:
....
default:
throw new IllegalStateException("oops, forgot to code something");
the default case is just good practice imho. :)

Related

NavigationView selected item color

i have two layouts that use a drawerLayout and they use the same code for the navigationView, the problem is that one of them changes the color of the selected item while the other doesn't even though it's the same exact code. here is the xml code:
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view_passager"
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/menu_passager" />
and java for the 1st layout:
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.acceuil_passager_item:
toolbar.setTitle("Accueil");
fm.beginTransaction().replace(R.id.frame_passager, new AcceuilPassagerFragment()).commit();
break;
case R.id.profile_item:
toolbar.setTitle("Profil");
fm.beginTransaction().replace(R.id.frame_passager, new PassagerProfileFragment()).commit();
break;
case R.id.historique_voyages_item_pass:
toolbar.setTitle("Historique des voyages");
fm.beginTransaction().replace(R.id.frame, new ListeTrajetsFragment()).commit();
break;
case R.id.futurs_voyages_item_pass:
toolbar.setTitle("Futurs voyages");
fm.beginTransaction().replace(R.id.frame_passager, new FutursVoyagesFragment()).commit();
break;
case R.id.log_out_item_pass:
Intent intent = new Intent(PassagerActivity.this, LoginActivity.class);
startActivity(intent);
mAuth.signOut();
finish();
Log.d(TAG, "onNavigationItemSelected: " + (mAuth == null));
break;
default:
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
and the java code for the 2nd layout :
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.acceuil_item_conducteur:
setUpToolbar(item);
fm.beginTransaction().replace(R.id.frame_conducteur, new AcceuilConducteurFragment()).commit();
break;
case R.id.profile_item_cond:
setUpToolbar(item);
fm.beginTransaction().replace(R.id.frame_conducteur, new ConducteurProfileFragment()).commit();
break;
case R.id.historique_voyages_item_cond:
setUpToolbar(item);
fm.beginTransaction().replace(R.id.frame_conducteur, new HistoriqueVoyagesFragment()).commit();
break;
case R.id.log_out_item_cond:
Intent intent = new Intent(ConducteurActivity.this, LoginActivity.class);
startActivity(intent);
mAuth.signOut();
finish();
Log.d(TAG, "onNavigationItemSelected: " + (mAuth == null));
break;
default:
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
and here is the first layout
and the 2nd one
ps: "Profil" is selected in both layouts
For navigation view you have to write a color selector like: nav_view_item_background
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/primary" android:state_checked="true" />
<item android:drawable="#android:color/transparent" />
</selector>
and set app:itemBackground="#drawable/nav_view_item_background"
For text color you have to same thing. Create a textColor selector and set app:itemTextColor
For Drawer Layout
return true (In Navigation item selection) change the color and selection.
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<group
android:id="#+id/menu_grp"
android:checkableBehavior="single">
Turned out checkableBehavior = "single" is what made the menu selected item checked and what was missing in my other layout

Group menu items work but don't display checkmark

I have a working app with an overflow menu. All the code in the menu works, but no checkmarks are being shown after I click on a single-clickable, grouped menu item.
Am I doing something fundamentally wrong? I thought that this displaying of the checkmark was automatic to Android and that the system would do this for me. Android knows it is in a group, it knows that only one can be selected, and it knows which one I selected! So..... Android should know how to display the checkmarks.
Code
XML
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".Calculator">
<group
android:checkableBehavior="single"
android:visible="true">
<item
android:id="#+id/ui_simple"
android:orderInCategory="100"
app:showAsAction="ifRoom|withText"
android:title="Regular"
android:checkable="true"/>
<item
android:id="#+id/ui_doge"
android:orderInCategory="100"
app:showAsAction="ifRoom|withText"
android:title="Doge"
android:checkable="true"/>
<item
android:id="#+id/ui_static"
android:orderInCategory="100"
app:showAsAction="ifRoom|withText"
android:title="Static"
android:checkable="true"/>
</group>
<item android:title="Display Mode"
android:orderInCategory="101" >
<menu>
<group android:checkableBehavior="single" android:visible="true" >
<item
android:id="#+id/mode_sign"
android:orderInCategory="100"
app:showAsAction="collapseActionView"
android:title="Sign Form"
android:checkable="true"/>
<item
android:id="#+id/mode_noun"
android:orderInCategory="100"
app:showAsAction="collapseActionView"
android:title="Noun Form"
android:checkable="true"/>
<item
android:id="#+id/mode_verb"
android:orderInCategory="100"
app:showAsAction="collapseActionView"
android:title="Verb Form"
android:checkable="true"/>
</group>
</menu>
</item>
</menu>
UI
Note: I have tried switching all the breaks to return true, but nothing happens.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.ui_simple :
startActivity(new Intent(this, Calculator.class));
break;
case R.id.ui_doge :
startActivity(new Intent(this, CalculatorDoge.class));
break;
case R.id.ui_static :
startActivity(new Intent(this, CalculatorStatic.class));
break;
case R.id.mode_sign : display = BinaryOperation.Display.SIGN; break;
case R.id.mode_verb : display = BinaryOperation.Display.VERB; break;
case R.id.mode_noun : display = BinaryOperation.Display.NOUN; break;
}
return super.onOptionsItemSelected(item);
}
While #Elltz provides a valuable solution to a problem in the code, there are a total of 2 issues in the code.
Problem 1
Do not set a checkable XML attribute in both the Menu Group and the individual MenuItems.
since in the XML there is <group android:checkableBehavior="single" it shows that radio buttons are desired; therefore, no item within the group should have android:checkable="true"
<group
android:checkableBehavior="single" <!-- ONLY HERE -->
android:visible="true" >
<item
android:id="#+id/mode_sign"
android:orderInCategory="100"
app:showAsAction="collapseActionView"
android:title="Sign Form" />
<item
android:id="#+id/mode_noun"
android:orderInCategory="100"
app:showAsAction="collapseActionView"
android:title="Noun Form"/>
<item
android:id="#+id/mode_verb"
android:orderInCategory="100"
app:showAsAction="collapseActionView"
android:title="Verb Form"/>
</group>
Problem 2
Again, #Elltz provides a good solution; however, it is slightly more complex than what it needs to be.
For Single Selection Only
switch (item.getItemId()) {
case R.id.ui_simple : startActivity(new Intent(this, Calculator.class)); return true;
case R.id.ui_doge : startActivity(new Intent(this, CalculatorDoge.class)); return true;
case R.id.ui_static : startActivity(new Intent(this, CalculatorStatic.class)); return true;
// Single Selection - Radio Buttons
case R.id.mode_sign :
item.setChecked(true); // ONLY THIS....HERE
display = BinaryOperation.Display.SIGN;
return true;
case R.id.mode_verb :
item.setChecked(true); // HERE
display = BinaryOperation.Display.VERB;
return true;
case R.id.mode_noun :
item.setChecked(true); // AND HERE
display = BinaryOperation.Display.NOUN;
return true;
default : return super.onOptionsItemSelected(item);
}
For Single OR Multi Selection
// Single OR Multi Select - Radio Buttons or CheckBoxes
switch (item.getItemId()) {
case R.id.ui_simple : startActivity(new Intent(this, Calculator.class)); return true;
case R.id.ui_doge : startActivity(new Intent(this, CalculatorDoge.class)); return true;
case R.id.ui_static : startActivity(new Intent(this, CalculatorStatic.class)); return true;
case R.id.mode_sign :
item.setChecked(!item.isChecked()); // LIKE THIS...HERE
display = BinaryOperation.Display.SIGN;
return true;
case R.id.mode_verb :
item.setChecked(!item.isChecked()); // HERE
display = BinaryOperation.Display.VERB;
return true;
case R.id.mode_noun :
item.setChecked(!item.isChecked()); // AND HERE
display = BinaryOperation.Display.NOUN;
return true;
default : return super.onOptionsItemSelected(item);
}
No
Menu items in the Icon Menu (from the options menu) cannot display a checkbox or radio button. If you choose to make items in the Icon Menu checkable, you must manually indicate the checked state by swapping the icon and/or text each time the state changes.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.ui_simple:
if (item.isChecked()){
item.setChecked(false);
}else{
item.setChecked(true);
}
startActivity(new Intent(this, Calculator.class));
break;
case R.id.ui_doge:
//same goes here and everyone
break;
....
}
}
Hope it helps

android submenu button item access before menu clicked

I have a submenu with buttons set up in xml which works fine.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Single menu item
Set id, icon and Title for each menu item
-->
<item android:id="#+id/menu_level"
android:title="Set Level" >
<menu>
<group android:checkableBehavior="single">
<item android:id="#+id/one"
android:checked="false"
android:title="One" />
<item android:id="#+id/two"
android:title="Two" />
<item android:id="#+id/three"
android:title="Three" />
</group>
</menu>
</item>
<item android:id="#+id/menu_save"
android:icon="#drawable/icon_save"
android:title="Save" />
<item android:id="#+id/menu_about"
android:icon="#drawable/icon_bookmark"
android:title="About">
<menu>
<item android:id="#+id/copyright"
android:title="(c) John Beukema 2012">
</item>
</menu>
<item/>
</menu>
I access it as follows:
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
Editor editor = PreferenceManager
.getDefaultSharedPreferences(this).edit();
switch (item.getItemId())
{
case R.id.menu_save:
return true;
case R.id.menu_recall:
return true;
case R.id.menu_level: {
return true;
}
case R.id.menu_about:
return true;
case R.id.one:
star = 1;
editor.putInt("Star", 1);
editor.commit();
item.setChecked(true);
return true;
case R.id.two:
star = 2;
editor.putInt("Star", 2);
editor.commit();
item.setChecked(true);
return true;
case R.id.three:
star = 3;
editor.putInt("Star", 3);
editor.commit();
item.setChecked(true);
return true;
case R.id.menu_delete:
return true;
case R.id.menu_preferences:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
So far no problem. But I want to load the buttons on start up from preferences.
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
star = preferences.getInt("Star", 1);
MenuItem one = (MenuItem) findViewById(R.id.one);
MenuItem two = (MenuItem ) findViewById(R.id.two);
MenuItem three = (MenuItem) findViewById(R.id.three);
switch(star)
{
case 1:
one.setChecked(true); break;
case 2:
two.setChecked(true); break;
case 3:
three.setChecked(true); break
}
}
}
This compiles but hangs. How do I address the submenu buttons?
I dont think you can do findviewbyid on menuitem. You need to set or unset the checked items in onprepareoptionsmenu

switch executes both cases in options menu

#Override
public boolean onMenuItemSelected(int featureId, MenuItem item)
{
switch(item.getItemId())
{
case R.id.item1: fukncijaD();
case R.id.item20: funkcijaOceni();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
//here is the xml for the menu
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="Зачувај"
android:id="#+id/item1"></item>
<item android:id="#+id/item20" android:title="Оцени"></item>
<item android:id="#+id/item3" android:title="Пост на ФБ"></item>
</menu>
When I check the value in case R.id.item1: fukncijaD(); it goes as it should with funckcijaD(), and then continues with the second case as if there were no cases...
Put break
switch(item.getItemId())
{
case R.id.item1:fukncijaD();break;
case R.id.item20:funkcijaOceni();break;
}

Android SubMenus not doing anything when clicked

I feel this may be a stupid question but I have no idea what to do.
I have a menu which works correctly. One of the items in the menu: "Search" brings up a submenu with different items like "Restaurant", "Cafe", etc.
Below is the XML code for creating the menu and sub menu:
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/new_entry"
android:title="#string/new_entry"
android:icon="#drawable/add_new">
</item>
<item android:id="#+id/search"
android:title="#string/search"
android:icon="#drawable/search">
<menu>
<item android:id="#+id/five"
android:title="#string/five">
</item>
<item android:id="#+id/ten"
android:title="#string/ten">
</item>
<item android:id="#+id/fifteen"
android:title="#string/fifteen">
</item>
<item android:id="#+id/restaurant"
android:title="#string/restaurant">
</item>
<item android:id="#+id/cafe"
android:title="#string/cafe">
</item>
<item android:id="#+id/sandwich"
android:title="#string/sandwich">
</item>
</menu>
</item>
<item android:id="#+id/info"
android:title="#string/info_short"
android:icon="#drawable/info">
</item>
Then in my Activity Class I have:
// Initialise Menu.
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_services, menu);
return true;
}
and:
// Create cases for each menu selection.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_entry:
createFood();
return true;
case R.id.search:
return true;
case R.id.cafe:
Log.d(TAG, "In Cafe SubMenu");
Toast.makeText(getApplicationContext(), TAG, Toast.LENGTH_SHORT);
return true;
case R.id.info:
info();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Each case in "onOptionsItemSelected" does what it is supposed to do, except "case R.id.cafe:" which is the submenu. Here it should post to the LogCat and a Toast for testing but does neither.
What am I missing?
Thanks
I have tried your code and it is working perfectly. Only the Toast is not displaying when I select 'cafe'. That is because, you did not call show() in your code. Your code is
Toast.makeText(getApplicationContext(), TAG, Toast.LENGTH_SHORT);
to show the toast on run time it should call as follows
Toast.makeText(getApplicationContext(), TAG, Toast.LENGTH_SHORT).show();
:)
I think you should remove following lines:
case R.id.search:
return true;

Categories

Resources