I would like to be able to keep the check in a menu when selecting an item, but when clicking it and then reopening the menu, the check disappeared.
image of the menu where I select an item
image where I reopen the menu but it is visually as if I had not clicked
here is the menu in java code
public void buttoninit(){
button1 = findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Para agregar un Popup Menu a un Button
PopupMenu popupMenu = new PopupMenu(mostrarActivity.this, button1);
popupMenu.getMenuInflater().inflate(R.menu.menu_filter_pa, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_pa_rut:
if (item.isChecked()) item.setChecked(false);
else item.setChecked(true);
a = 1;
break;
case R.id.menu_pa_nombre:
if (item.isChecked()) item.setChecked(false);
else item.setChecked(true);
a = 2;
break;
case R.id.menu_pa_apellido:
if (item.isChecked()) item.setChecked(false);
else item.setChecked(true);
a = 3;
break;
default:
return false;
}
return true;
}
});
popupMenu.show();
}
});
}
here is the Menu in XML
<group android:checkableBehavior="single">
<item
android:id="@ id/menu_pa_rut"
android:icon="@drawable/ic_filter_list"
android:title="Rut"
app:showAsAction="ifRoom">
</item>
<item
android:id="@ id/menu_pa_nombre"
android:icon="@drawable/ic_filter_list"
android:title="Nombre"
app:showAsAction="ifRoom">
</item>
<item
android:id="@ id/menu_pa_apellido"
android:icon="@drawable/ic_filter_list"
android:title="Apellido"
app:showAsAction="ifRoom">
</item>
</group>
CodePudding user response:
Whenever you will click on button to populate option menu it will reinitialize every time and default value and checks will be applied. You will have to store click position for the clicked radio button of menu and set checked accordingly.
Or initialize your popup option menu only once by declaring it globally.
CodePudding user response:
you have to move your code out of setOnClickListener just keep popupMenu.show() and if you want to save your ui state or menu, the better way is to use a live data and viewModel. the live data keeps value even if configuration changes.