NavigationView, multiple menus - android

I'm trying to use the NavigationView in one of my projects to implement a side menu. The app has two type of users: Admin and User.
I created the login activity and I log in as user or admin. I pass the name, email via intent (putExtra) to my NavigationActivity.
Since I have two type of users I created two type of menus (admin has more menu options).
I check the content of the passed value from the intent and inflate the navigation views menu accordingly.
My problem is I don't know how to separate in the listener the two type of menus. Should I create in my if else two listeners for each case? What would be the right approach? The way I did it doesn't work correctly, in my side menu I have the first two items from the user menu and after that the reamining items of the admin menu.
Here's thecode:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
Bundle extras = getIntent().getExtras();
String name = extras.getString("name");
String email = extras.getString("email");
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
if(name.equals("admin")){
// listener for admin here?
navigationView.inflateMenu(R.menu.admin_drawer);
}else{
// listener for user here?
navigationView.inflateMenu(R.menu.user_drawer);
}
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// questionable part here, doesn't work correctly
#Override
public boolean onNavigationItemSelected(MenuItem item) {
if(item.isChecked())
item.setChecked(false);
drawerLayout.closeDrawers();
switch (item.getItemId()){
// this is for user
case R.id.test:
Toast.makeText(getApplicationContext(), "Test Selected", Toast.LENGTH_SHORT).show();
TestFragment testFragment = new TestFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frameholder, testFragment);
fragmentTransaction.commit();
return true;
// this is for user
case R.id.practice:
Toast.makeText(getApplicationContext(),"Practice Selected",Toast.LENGTH_SHORT).show();
break;
// this is for admin
case R.id.existing_questions:
Toast.makeText(getApplicationContext(),"Questions Selected",Toast.LENGTH_SHORT).show();
break;
// this is for admin
case R.id.new_questions:
Toast.makeText(getApplicationContext(),"New questions Selected",Toast.LENGTH_SHORT).show();
break;
// this is for admin
case R.id.settings:
Toast.makeText(getApplicationContext(),"Settings Selected",Toast.LENGTH_SHORT).show();
break;
// this is for admin
case R.id.users_data:
Toast.makeText(getApplicationContext(),"User data Selected",Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
Edit:
Here you have the two menus I use:
admin_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/existing_questions"
android:checked="false"
android:icon="#drawable/ic_existq"
android:title="Questions" />
<item
android:id="#+id/new_questions"
android:checked="false"
android:icon="#drawable/ic_addq"
android:title="Add question" />
<item
android:id="#+id/settings"
android:checked="false"
android:icon="#drawable/ic_settings"
android:title="Settings" />
<item
android:id="#+id/users_data"
android:checked="false"
android:icon="#drawable/ic_statistics"
android:title="Statistics" />
</group>
</menu>
user_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/test"
android:checked="false"
android:icon="#drawable/ic_test"
android:title="Test" />
<item
android:id="#+id/practice"
android:checked="false"
android:icon="#drawable/ic_practice"
android:title="Practice" />
</group>
</menu>

A good approach would be to use two groups with different IDs in the same menu. Then you can switch between them easly with .setGroupVisible() like this:
if(name.equals("admin")){
navigationView.menu.setGroupVisible(R.id.menu_group_admin, true);
navigationView.menu.setGroupVisible(R.id.menu_group_user, false);
}
else{
navigationView.menu.setGroupVisible(R.id.menu_group_admin, false);
navigationView.menu.setGroupVisible(R.id.menu_group_user, true);
}
This works seamlessly

Thanks cylon. The mistake was made by me. I inflated the navigation view in the xml, and then from code to.

Related

NavigationView item selector does not highlight the enabled item

I'm trying to change the text color of the selected item in the NavigationView. Using the information for the previous topic I set a selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/primaryColor" android:state_checked="true" />
<item android:color="#color/lightGrayColor" android:state_checked="false" />
</selector>
The primaryColor is blue. The NavigationView is as follows:
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/activity_nav_header"
app:menu="#menu/nev_menu"
app:itemIconTint="#drawable/menu_item_selector"
app:itemTextColor="#drawable/menu_item_selector" />
</androidx.drawerlayout.widget.DrawerLayout>
As you can see I set app:itemTextColor to menu_item_selector. But when I run the application, I see the selected item as grey. How does the NavigationView know which screen am I seeing right now? How do I fix it?
I'm using onNavigationItemSelected to switch between activities. Also I currently have only two windows - the dashboard and the logout. From the main screen I move to the dashboard (which contains the menu) and using the logout I go back to the main screen. Maybe the reason for it not working is because it does not know that the current screen is dashboard?
The dashboard java cotnains the following method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
toolBar = findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolBar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View hView = navigationView.getHeaderView(0);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.dashboard:
// CURRENT ACTIVITY
break;
case R.id.messages:
startActivity(new Intent(this, MessagesActivity.class));
break;
case R.id.settings:
startActivity(new Intent(this, SettingsActivity.class));
break;
case R.id.about:
startActivity(new Intent(this, AboutActivity.class));
break;
case R.id.logout:
startActivity(new Intent(this, MainActivity.class));
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
For the initial look, you set a checked color to primaryColor, but overwrite it with lightGrayColor as you didn't specify the state that this color is available at; so you need to specify the state by android:state_checked="false"
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/primaryColor" android:state_checked="true" />
<item android:color="#color/lightGrayColor" android:state_checked="false"/>
</selector>
You can also set the default selected item at the app start by trying any of:
navigationView.getMenu().getItem(0).setChecked(true);
navigationView.setCheckedItem(R.id.nav_item);
Update
This is how it works with me
Step 1: Use the same selector:
selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/primaryColor" android:state_checked="true" />
<item android:color="#color/lightGrayColor" android:state_checked="false" />
</selector>
Step 2: use the xml attribute app:itemTextColor within NavigationView widget
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/navigation_header_layout"
app:itemTextColor="#drawable/selector"
app:menu="#menu/navigation_menu" />
Step 3:
The previous step attribute won't work automatically as for some reason when you hit an item from the NavigationView menu, it doesn't consider this as a button check. So you need to manually get the selected item checked and clear the previously selected item. Use below listener to do that
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
// remove all colors of the items to the `unchecked` state of the selector
removeColor(mNavigationView);
// check the selected item to change its color set by the `checked` state of the selector
item.setChecked(true);
switch (item.getItemId()) {
case R.id.dashboard:
// CURRENT ACTIVITY
break;
case R.id.messages:
startActivity(new Intent(this, MessagesActivity.class));
break;
case R.id.settings:
startActivity(new Intent(this, SettingsActivity.class));
break;
case R.id.about:
startActivity(new Intent(this, AboutActivity.class));
break;
case R.id.logout:
startActivity(new Intent(this, MainActivity.class));
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
private void removeColor(NavigationView view) {
for (int i = 0; i < view.getMenu().size(); i++) {
MenuItem item = view.getMenu().getItem(i);
item.setChecked(false);
}
}
Now the text color will change perfectly.
Step 4:
To change icon colors, use the app:iconTint attribute in the NavigationView menu items, and set to the same selector.
<?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/nav_account"
android:checked="true"
android:icon="#drawable/ic_person_black_24dp"
android:title="My Account"
app:iconTint="#drawable/selector" />
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_settings_black_24dp"
android:title="Settings"
app:iconTint="#drawable/selector" />
<item
android:id="#+id/nav_logout"
android:icon="#drawable/logout"
android:title="Log Out"
app:iconTint="#drawable/selector" />
</menu>
Result:

Not able to get navigation drawer item id to open an activity

I am trying to get my app to work to open my activity to click on the navigation drawer but I am not able to get the menu id.
.java
navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.home_id:
Toast.makeText(MainActivity.this, "tarun", Toast.LENGTH_SHORT).show();
Intent home_Intent = new Intent(MainActivity.this,MainActivity.class);
startActivity(home_Intent);
break;
return true;
}
});
This is my menu item xml here is also provide the id and the name which will show me in navigation view
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/home_id"
android:title="Home"
android:icon="#drawable/home"/>
</group>
</menu>

NavigationView slow to open / Skipping frames (Android Design Lib)

I'm using a NavigationView supplied by the Android Design Library. I've found after adding a few items to it that is performing quite poorly. On first launch it takes a second or so to open for the firs time. Here's a screenshot of the UI.
I'll try to post some of the relevant bits of code.
Drawer XML
<group android:checkableBehavior="single">
<item
android:id="#+id/home"
android:checked="false"
android:icon="#drawable/ic_home"
android:title="Home" />
<item
android:id="#+id/about"
android:checked="false"
android:icon="#drawable/ic_about"
android:title="About" />
<item
android:id="#+id/gallery"
android:checked="false"
android:icon="#drawable/ic_gallery"
android:title="Gallery" />
<item
android:id="#+id/settings"
android:icon="#drawable/ic_action_settings"
android:title="Settings" />
<item
android:id="#+id/navigation_subheader"
android:title="Categories">
<menu>
<item
android:id="#+id/science"
android:checked="false"
android:icon="#drawable/ic_science"
android:title="Science" />
<item
android:id="#+id/parenting"
android:checked="false"
android:icon="#drawable/ic_parenting"
android:title="Parenting" />
<item
android:id="#+id/android"
android:checked="false"
android:icon="#drawable/ic_android"
android:title="Android" />
<item
android:id="#+id/technology"
android:checked="false"
android:icon="#drawable/ic_tech"
android:title="Technology" />
<item
android:title=""
android:checkable="false"
android:visible="false"
android:orderInCategory="200"/>
</menu>
</item>
</group>
MainAct
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
Log.v(TAG + "-S", "Pre_Switch = " + mCurCheckPosition);
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
case R.id.home:
homeFragment();
return true;
case R.id.about:
webFragment();
return true;
case R.id.gallery:
galleryFragment();
return true;
case R.id.science:
scienceFragment();
return true;
case R.id.parenting:
parentingFragment();
return true;
case R.id.android:
androidFragment();
return true;
case R.id.technology:
technologyFragment();
return true;
case R.id.settings:
Intent i = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(i);
default:
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.openDrawer, R.string.closeDrawer){
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
And finally here is the error im seeing in the logs from the Choreographer, i'm hoping this is just a bug in the lib however im wondering if someone else came across this and might have a work around.
I/Choreographer﹕ Skipped 117 frames! The application may be doing too much work on its main thread.
Full source is available here: https://github.com/caman9119/The_Jones_Theory
Found the issue in my header.xml I was using a background.png that was 1080x720p. I scaled the image down to ~400x300 and voila, interesting problem indeed.
If you are using dynamic images for the background (using user facebook or g+ banner by example) and using Picasso this piece of code can be usefull:
ImageView background = (ImageView) findViewById(R.id.background);
Picasso
.with(context)
.load([Your image source here])
.fit()
.centerCrop()
.into(background)
Had the same problem, i was using 512 x 512 images in the drawer list. All images were initially placed in the 'drawable' folder but when i moved them to the 'drawable-xxhdpi' folder, it was butter smooth.

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

Having two single-selection groups in ActionBar doesn't work, but attaching a pop up menu instead doesn't work either

I am writing an Android app where the user must choose how and what to display on a graph. These options are expressed in two single-selection menu groups (radio buttons), both of which should be accessible from the action bar.
The first group works fine. It's added at the end of my ActionBar XML like this:
<group android:checkableBehavior="single" android:showAsAction="never" >
<item android:id="#+id/menu_choice_1" android:title="Choice 1" />
<item android:id="#+id/menu_choice_2" android:title="Choice 2" android:checked="true"/>
</group>
When I add a second <group> below the first one, however, the two merge into one single-selection list. In other words, the options from both lists are rendered together and if I choose an option pertaining to the first list, I cannot choose anything from the second.
Instead, I want two separate lists of radio buttons. My next idea was to add another button the ActionBar that, when clicked, would launch a pop-up menu. But when I click the button, I get an IllegalStateException, saying that my "MenuPopupHelper cannot be used without an anchor".
Here is my attempted pop-up menu code:
In my ActionBar XML:
<item android:id="#+id/menu_openothermenu"
android:title="#string/openothermenustr"
android:showAsAction="always" />
My new menu XML:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item android:id="#+id/menu_2_choice_1" android:title="#string/2_choice_1" />
<item android:id="#+id/menu_2_choice_2" android:title="#string/2_choice_2" android:checked="true"/>
</group>
</menu>
Code in my Activity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor;
switch (item.getItemId()) {
case R.id.openothermenu:
Menu m = (Menu) findViewById(R.menu.other_menu);
PopupMenu popup = new PopupMenu(this, findViewById(R.menu.main_menu));
popup.setOnMenuItemClickListener(this);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.other_menu, popup.getMenu());
/* This commented block doesn't work either, and prevents execution
// Restore saved chosen value
int chosen = settings.getInt(MENU_2_PREFS, -1);
switch(chosen)
{
case 1:
m.findItem(R.id.menu_1_choice_1).setChecked(true);
updateVisibleThings();
break;
default:
case 2:
m.findItem(R.id.menu_2_choice_2).setChecked(true);
updateOtherVisibleThings();
break;
}
*/
popup.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onMenuItemClick(MenuItem item) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor;
switch(item.getItemId()) {
case R.id.menu_2_choice_1:
if (item.isChecked()) item.setChecked(false);
else item.setChecked(true);
updateVisibleThings();
// save chosen setting
editor = settings.edit();
editor.putInt(MENU_2_PREFS, 1);
editor.commit(); // Commit the edits!
return true;
case R.id.menu_2_choice_2:
if (item.isChecked()) item.setChecked(false);
else item.setChecked(true);
updateOtherVisibleThings();
// save chosen setting
editor = settings.edit();
editor.putInt(MENU_2_PREFS, 2);
editor.commit(); // Commit the edits!
return true;
default:
return true;
}
}
How can I create two sets of checkable menu items such that both are attached to the ActionBar?
I found an elegant way to solve this that was unfortunately not in the documentation. Add the following code to your ActionBar menu XML:
<item android:id="#+id/menu_openothermenu"
android:title="#string/openothermenustr"
android:showAsAction="always">
<menu>
<group android:checkableBehavior="single">
<item android:id="#+id/menu_2_choice_1" android:title="#string/2_choice_1" android:showAsAction="never" />
<item android:id="#+id/menu_2_choice_2" android:title="#string/2_choice_2" android:showAsAction="never" android:checked="true" />
</group>
</menu>
</item>
No extra handler code or popup menu implementation is necessary for such a menu to appear.

Categories

Resources