Android PopupMenu checked item does not check

I have this simple PopupMenu, but when I click on an element, the element is not checked. Why?

The documentation has: Menu items in the icon menu (from the options menu) cannot display a check box or radio button. Shows a radio button, but only the state does not change ...

Java

public void showSortPopup() { View menuItemView = findViewById(R.id.action_sort); PopupMenu popup = new PopupMenu(this, menuItemView); popup.inflate(R.menu.sort); popup.getMenu().findItem(R.id.sort_def).setChecked(true); popup.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.sort_def: sortOrder = CardCursorContract.CardCursor.DEFAULT_SORT; mCardsFragment.setSortOrder(sortOrder); savePref(); if (item.isChecked()) item.setChecked(false); else item.setChecked(true); break; case R.id.sort_asc: sortOrder = CardCursorContract.CardCursor.ALPHABETICAL_ASC_SORT; mCardsFragment.setSortOrder(sortOrder); savePref(); if (item.isChecked()) item.setChecked(false); else item.setChecked(true); break; case R.id.sort_desc: sortOrder = CardCursorContract.CardCursor.ALPHABETICAL_DESC_SORT; mCardsFragment.setSortOrder(sortOrder); savePref(); if (item.isChecked()) item.setChecked(false); else item.setChecked(true); break; default: break; } return false; } }); popup.show(); } 

Xml file

 <menu xmlns:android="http://schemas.android.com/apk/res/android"> <group android:checkableBehavior="single"> <item android:id="@+id/sort_def" android:title="@string/action_sort_def" android:orderInCategory="1" android:showAsAction="always" /> <item android:id="@+id/sort_asc" android:title="@string/action_sort_name" android:orderInCategory="2" android:showAsAction="always" /> <item android:id="@+id/sort_desc" android:title="@string/action_sort_name_desc" android:orderInCategory="3" android:showAsAction="always"/> </group> 

Screen

enter image description here

+6
source share
2 answers

First of all, you can simplify the if checked else statement for

 item.setChecked(!item.isChecked()) 

That way, it will always switch it from true → false and vice versa.

But the problem is that you have radio lenses, which makes the above statement, does the group check, but you want the item checked.

To get the behavior you're looking for, you can use item.getSubmMenu() and then use the setChecked method for the specific subMenuItem you want.

For instance:

 //This will refer to the default, ascending or descending item. MenuItem subMenuItem = item.getSubMenu().getItem(INDEX_OF_ITEM); //Check or uncheck it. subMenuItem.setChecked(!subMenuItem.isChecked()); 
+2
source

** Change these lines in each case **

 if (item.isChecked()) item.setChecked(false); else item.setChecked(true); 

TO

 if (item.isChecked()) item.setChecked(true); else item.setChecked(false); 
0
source

Source: https://habr.com/ru/post/972129/


All Articles