I have a button that opens a context menu with a list of various options. Only one parameter can be selected at a time, so I want a button next to each of them to switch which element is currently selected. When I select an item from the context menu, the switch selects and closes. As soon as I press the button to open the context menu, the previously selected item is not selected.
How do I get the context menu to remember which item was selected earlier?
Secondly, when an activity is first created, the default option is selected. How to set the initial default value that can be overwritten when another item of the context menu is selected? I can set android:checked="true" in XML, but can it be overwritten when another element is selected?
Java:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.browse); Button buttonView = (Button) this.findViewById(R.id.button_view); buttonView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { registerForContextMenu(v); openContextMenu(v); } }); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle(R.string.menu_title); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); } @Override public boolean onContextItemSelected(MenuItem item) { switch(item.getItemId()) { case(R.id.item1): if(item.isChecked()) { item.setChecked(false); } else { item.setChecked(true); } break; case(R.id.item2): if(item.isChecked()) { item.setChecked(false); } else { item.setChecked(true); } break; case(R.id.item3): if(item.isChecked()) { item.setChecked(false); } else { item.setChecked(true); } break; default: return super.onContextItemSelected(item); } return true; }
XML:
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <group android:id="@+id/context_menu" android:checkableBehavior="single"> <item android:id="@+id/item1" android:title="@string/context_menu_item1" /> <item android:id="@+id/item2" android:title="@string/context_menu_item2" /> <item android:id="@+id/item3" android:title="@string/context_menu_item3" /> </group> </menu>
Any help would be greatly appreciated!
source share