How to save instance state of selected radiobutton on menu - android

I have options menu in my toolbar with radibutton item :
<item
android:id="#+id/map_menu"
android:icon="#drawable/ic_layer"
android:orderInCategory="102"
app:showAsAction="always"
android:title="#string/action_settings">
<menu>
<group
android:id="#+id/map_types_group"
android:checkableBehavior="single" >
<item
android:id="#+id/map_terrain"
android:orderInCategory="1"
app:showAsAction="ifRoom"
android:title="#string/map_terrain"/>
<item
android:id="#+id/map_normal"
android:orderInCategory="2"
android:checked="true"
app:showAsAction="ifRoom"
android:title="#string/map_normal"/>
<item
android:id="#+id/map_hybrid"
android:orderInCategory="3"
app:showAsAction="ifRoom"
android:title="#string/map_hybrid"/>
</group>
</menu>
</item>
I want to restore selected radiobutton when orientation change happened in onSaveInstanceState,onRestoreInstanceState but i can't understand how to get selected button from radiogroup in options menu.

Here is a fully working and tested example. With this code in place, no matter how many times you rotate the screen, the currently selected item will persist.
First, create these instance variables to keep track of the state of the menu and have a name for the preference you will be saving in the Bundle:
private final static String MENU_SELECTED = "selected";
private int selected = -1;
MenuItem menuItem;
The saveInstanceState() method should save off the currently selected value:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt(MENU_SELECTED, selected);
super.onSaveInstanceState(savedInstanceState);
}
Update the currently selected item in onOptionsItemSelected():
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Log.d("settings", "id: " + id);
return true;
}
if (id == R.id.map_terrain){
Log.d("menuitem", "terrain id: " + id);
selected = id;
item.setChecked(true);
return true;
}
if (id == R.id.map_normal){
Log.d("menuitem", "normal id: " + id);
selected = id;
item.setChecked(true);
return true;
}
if (id == R.id.map_hybrid){
Log.d("menuitem", "hybrid id: " + id);
selected = id;
item.setChecked(true);
return true;
}
return super.onOptionsItemSelected(item);
}
In onCreate(), load the saved data if it exists:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null){
selected = savedInstanceState.getInt(MENU_SELECTED);
}
}
And then re-select the previously selected item in onCreateOptionsMenu():
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
if (selected == -1){
return true;
}
switch (selected){
case R.id.map_terrain:
menuItem = (MenuItem) menu.findItem(R.id.map_terrain);
menuItem.setChecked(true);
break;
case R.id.map_normal:
menuItem = (MenuItem) menu.findItem(R.id.map_normal);
menuItem.setChecked(true);
break;
case R.id.map_hybrid:
menuItem = (MenuItem) menu.findItem(R.id.map_hybrid);
menuItem.setChecked(true);
break;
}
return true;
}

MenuItem in onOptionsItemSelected has item.isChecked() method, just use it. You can store one boolean field(it wouldn't be a bad thing in my opinion) and change it whenever change in radiog group occurs
Then you can have your id by simply calling:
if(item.isChecked()) {
your_id_field = item.getItemId()
}

Create a variable eg: menu_selection to store the id of the menu item selected. Initially you can define 0
private int menu_selection = 0;
Save and restore the value of the variable using onSaveInstanceState and onRestoreInstanceState
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the id of radio button selected in the menu
savedInstanceState.putInt("selection", menu_selection);
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
menu_selection = savedInstanceState.getInt("selection");
}
In onOptionsItemSelected , assign the id of the menu item selected item.getItemId() to the variable
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
if (item.isChecked()) {
item.setChecked(false);
} else {
item.setChecked(true);
menu_selection = item.getItemId();
}
switch (item.getItemId()) {
case R.id.map_terrain:
//some action here
return true;
case R.id.map_normal:
//some action here
return true;
case R.id.map_hybrid:
//some action here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
In onCreateOptionsMenu , find the menu item identified with the value in the variable and check it
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
if (menu_selection != 0) {
MenuItem selected = (MenuItem) menu.findItem(menu_selection);
selected.setChecked(true);
}
return true;
}

Related

open a menu from OnClickListener

I want to open a menu from a OnClickListener
without using the method onCreateOptionsMenu
My code:
toolbar.setNavigationIcon(R.drawable.week); //your icon
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v ) {
}
});
Thanks in advance!
I think you want to show/hide a menu item based on actions from users. To do that you must use onCreateOptionsMenu and whenever you want to show/hide the menu item, then call invalidateOptionsMenu (this method will call onCreateOptionsMenu again).
boolean mShowMenu = false;
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.your_menu, menu);
MenuItem item = menu.findItem(R.id.your_menu_item);
item.setVisible(showMenu);
return true;
}
And in your code, when you want to show menu item.
toolbar.setNavigationIcon(R.drawable.week); //your icon
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v ) {
mShowMenu = true;
invalidateOptionsMenu();
}
});
And give it a try.
You should need to create menu Interface in xml File Like this
<item
android:id="#+id/settings"
android:title="Setting"
app:showAsAction="never" />
<item
android:id="#+id/my_activity"
android:title="My Activity"
app:showAsAction="always"
android:icon="#android:drawable/btn_radio"/>
After that in the Java code of a particular class You need to create the code like this;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.my_activity) {
Intent intent1 = new Intent(this,MyActivity.class);
this.startActivity(intent1);
return true;
}
if (id == R.id.settings) {
Toast.makeText(this, "Setting", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
Hopefully this may resolve your problem

Changing options menu icon

Lets say I have a options menu like below:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home_page, menu);
final MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) myActionMenuItem.getActionView();
mSearchView.setQueryHint("Enter text to search(min. 3 chars)...");
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(final String searchQuery) {
if (!mSearchView.isIconified()) {
mSearchView.setIconified(true);
}
mSearchView.setQuery(searchQuery, false);
return false;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
saveState();
finish();
} else if (item.getItemId() == R.id.action_bookmark) {
FragmentAdapter adapter = (FragmentAdapter) mViewPager.getAdapter();
PageFragment fragment = (PageFragment)adapter.instantiateItem(mViewPager,mViewPager.getCurrentItem());
fragment.getContent();
Toast.makeText(this, "Bookmark Added", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
Is there any way to check which icon set to options menu item also change it with another when clicked on it?
here is xml for options menu:
<item
android:id="#+id/action_bookmark"
android:title="Bookmark"
app:showAsAction="always|collapseActionView"
android:icon="#drawable/ic_bookmark_empty" />
onclicking i want to check which icon bookmark has and change it.
if you want to check which drawable is currently set you can use this code
item.getIcon().getConstantState().equals
(getResources().getDrawable(R.drawable.ic_bookmark_empty).getConstantState())
and for setting new drawable you can use this code
item.setIcon(R.drawble.ic_bookmark_empty)
You need to check the following condition in onOptionsItemSelected :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
saveState();
finish();
} else if (item.getItemId() == R.id.action_bookmark) {
if(item.getIcon() ==R.drawable.ic_bookmark_empty)
{
// call bookmark code
item.setIcon(R.drawable.ic_bookmark_filled); // set your desired bookmark icon
} else {
// call remove bookmark code
item.setIcon(R.drawable.ic_bookmark_empty);
}
FragmentAdapter adapter = (FragmentAdapter) mViewPager.getAdapter();
PageFragment fragment = (PageFragment)adapter.instantiateItem(mViewPager,mViewPager.getCurrentItem());
fragment.getContent();
Toast.makeText(this, "Bookmark Added", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
You can use this code menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.ic_bookmark_empty));

How to use CheckBox in the menu in Android?

I am new to Android. I want to use a checkbox in the menu which has to be checked and unchecked while the user touching. And I need to perform some actions if the check box is checked. Right now I have a checkbox that is checked when the program is run.
I have managed to insert checkbox in the menu and got it to be checked when the app starts, just as it should. But when I try to uncheck it, the program crashes.
Menu.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/checkBox1"
android:showAsAction="never"
android:title="Allow Check"
android:checkable="true"
android:checked="true" />
<item
android:id="#+id/action_help"
android:orderInCategory="100"
android:showAsAction="never"
android:title="Hai"/>
<item
android:id="#+id/checkBox2"
android:showAsAction="never"
android:title="Allow Check 2"
android:checkable="true"
android:checked="true" />
</menu>
MainActivity.cs
public override bool OnCreateOptionsMenu (IMenu menu)
{
base.OnCreateOptionsMenu (menu);
MenuInflater inflater = this.MenuInflater;
inflater.Inflate (Resource.Menu.menu, menu);
return true;
}
public override bool OnOptionsItemSelected (Android.Views.IMenuItem item)
{
switch (item.ItemId) {
case Resource.Id.action_help:
return true;
case Resource.Id.checkBox1:
CheckBox check1 = (CheckBox)FindViewById (Resource.Id.checkBox1);
//Here the check1 come as null, which leads to the crash.
if (check1.Checked == true)
check1.Checked = false;
else
check1.Checked = true;
check1.Click += check1_Click;
return true;
case Resource.Id.checkBox2:
CheckBox check2 = (CheckBox)FindViewById (Resource.Id.checkBox2);
if (check2.Checked == true)
check2.Checked = false;
else
check2.Checked = true;
check2.Click += check2_Click;
return true;
default:
return base.OnOptionsItemSelected (item);
}
}
While trying to retrieve the checkbox declared in the menu, it comes as null. How can I get this working?
Please use code snippet , may this help you
public override bool OnOptionsItemSelected (Android.Views.IMenuItem item)
{
switch (item.ItemId) {
case Resource.Id.action_help:
return true;
case Resource.Id.checkBox1:
if (item.IsChecked)
item.SetChecked(false);
else
item.SetChecked(true);
item.Click += check1_Click;
return true;
case Resource.Id.checkBox2:
if (item.IsChecked)
item.SetChecked(false);
else
item.SetChecked(true);
item.Click += check2_Click;
return true;
default:
return base.OnOptionsItemSelected (item);
}
}
Try getting the checked state of the item by calling item.IsChecked .
You have to attach those controls in you OnCreate()
public class MainActivity : Activity
{
private CheckBox check1;
private CheckBox check2;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Create your application here
SetContentView(Resource.Layout.yourLayout);
//find controls in here
check1 = (CheckBox)FindViewById (Resource.Id.checkBox1);
check2 = (CheckBox)FindViewById (Resource.Id.checkBox2);
}
....
and then do your checks
public override bool OnOptionsItemSelected (Android.Views.IMenuItem item)
{
switch (item.ItemId) {
case Resource.Id.action_help:
return true;
case Resource.Id.checkBox1:
if (check1.Checked == true)
check1.Checked = false;
else
check1.Checked = true;
check1.Click += check1_Click;
return true;
case Resource.Id.checkBox2:
if (check2.Checked == true)
check2.Checked = false;
else
check2.Checked = true;
check2.Click += check2_Click;
return true;
default:
return base.OnOptionsItemSelected (item);
}
}

Hide Items in Context Action Bar (CAB) dynamically when multiple items are selected

I have a listActivity that shows CAB on long click. If more than 1 item is selected I would like to hide one of my menu items.
I keep track of the # of items selected in onItemCheckedStateChanged(). However I don't have access to the menu to remove the item from this function. See comments in code below to get an idea of what I was trying. I feel like I am missing some simple core understanding... code below is called from my onCreate() function.
private void setupActionBarContext() {
ListView listView = getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
private int selCount = 0;
ArrayList<Long> idList = new ArrayList<Long>();
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
if (checked) {
selCount++;
idList.add(id);
} else {
selCount--;
idList.remove(id);
}
mode.setTitle(selCount + " selected");
// I WOULD LIKE TO HIDE ITEM ON MENU IF 'selCount' IS > 1
// For example something like this...
// if (selCount > 1) {
// MenuItem item = menu.findItem(R.id.edit_item);
// item.setVisible(false);
// } else {
// MenuItem item = menu.findItem(R.id.edit_item);
// item.setVisible(false);
// }
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.delete_item:
for(Long i: idList){
mDbHelper.deleteItem(i);
}
mode.finish();
return true;
case R.id.edit_item:
Toast.makeText(getBaseContext(), "Edit Item", Toast.LENGTH_SHORT).show();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate the menu for the CAB
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
selCount = 0;
idList.clear();
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
});
And my menu item...
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/edit_item"
android:title="#string/edit_item"
android:showAsAction="ifRoom"
android:orderInCategory="1"/>
<item android:id="#+id/delete_item"
android:title="#string/delete_item"
android:icon="#drawable/ic_action_delete"
android:showAsAction="ifRoom"
android:orderInCategory="2"/>
</menu>
As suggested in adneal's comment.
Add invalidate() to onItemCheckedStateChanged()
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
if (checked) {
selCount++;
idList.add(id);
} else {
selCount--;
idList.remove(id);
}
mode.setTitle(selCount + " selected");
mode.invalidate(); // Add this to Invalidate CAB
}
This invalidates the CAB and causes the onPrepareActionMode() function to be called.
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
if (selCount == 1){
MenuItem item = menu.findItem(R.id.edit_item);
item.setVisible(true);
return true;
} else {
MenuItem item = menu.findItem(R.id.edit_item);
item.setVisible(false);
return true;
}
}

How can I dynamically create menu items?

I'm building an Android application and I'm trying to build a user management system where users can login, logout, etc. I want to display a login menu item if the user is logged out and a logout button if the user is logged in. How can I do this dynamically?
This is the layout file right now:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/add" android:title="Add" android:icon="#drawable/ic_menu_add"/>
<item android:id="#+id/list" android:title="List" android:icon="#drawable/ic_menu_list"/>
<item android:id="#+id/refresh" android:title="Refresh" android:icon="#drawable/ic_menu_refresh"/>
<item android:id="#+id/login" android:title="Login" android:icon="#drawable/ic_menu_login"/>
</menu>
This is my Java right now:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.activity_main, menu);
return(super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
System.out.println(item.getItemId()==R.id.add);
if (item.getItemId()==R.id.add)
{
//Cannot add spot unless we have obtained the users current location.
if((currentLat != 0) && (currentLng != 0))
{
System.out.println("loggedin? : " + auth.isLoggedIn());
if(!auth.isLoggedIn())
{
Toast.makeText(MainActivity.this, "You must be logged in to add a new spot",
Toast.LENGTH_LONG).show();
}
else
{
Intent addIntent = new Intent(MainActivity.this, AddSpot.class);
Bundle b = new Bundle();
b.putDouble("currentLat", currentLat);
b.putDouble("currentLng", currentLng);
addIntent.putExtras(b);
startActivity(addIntent);
return(true);
}
}
}
else if(item.getItemId()==R.id.list)
{
//Pointless showing them a blank screen if nothing is retrieved from the server
if(list != null)
{
Intent listIntent = new Intent(MainActivity.this, ListLocations.class);
listIntent.putExtra("list", list);
startActivity(listIntent);
return(true);
}
}
if(item.getItemId()==R.id.refresh)
{
finish();
startActivity(getIntent());
return(true);
}
if(item.getItemId()==R.id.login)
{
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
return(true);
}
return(super.onOptionsItemSelected(item));
}
How to Dynamically Add Menu Items to an Android Activity
public class yourActivity extends Activity {
...
private static final int MENU_ADD = Menu.FIRST;
private static final int MENU_LIST = MENU.FIRST + 1;
private static final int MENU_REFRESH = MENU.FIRST + 2;
private static final int MENU_LOGIN = MENU.FIRST + 3;
/**
* Use if your menu is static (i.e. unchanging)
*/
/*
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_ADD, Menu.NONE, R.string.your-add-text).setIcon(R.drawable.your-add-icon);
menu.add(0, MENU_LIST, Menu.NONE, R.string.your-list-text).setIcon(R.drawable.your-list-icon);
menu.add(0, MENU_REFRESH, Menu.NONE, R.string.your-refresh-text).setIcon(R.drawable.your-refresh-icon);
menu.add(0, MENU_LOGIN, Menu.NONE, R.string.your-login-text).setIcon(R.drawable.your-login-icon);
return true;
}
*/
/**
* Gets called every time the user presses the menu button.
* Use if your menu is dynamic.
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
if(enableAdd)
menu.add(0, MENU_ADD, Menu.NONE, R.string.your-add-text).setIcon(R.drawable.your-add-icon);
if(enableList)
menu.add(0, MENU_LIST, Menu.NONE, R.string.your-list-text).setIcon(R.drawable.your-list-icon);
if(enableRefresh)
menu.add(0, MENU_REFRESH, Menu.NONE, R.string.your-refresh-text).setIcon(R.drawable.your-refresh-icon);
if(enableLogin)
menu.add(0, MENU_LOGIN, Menu.NONE, R.string.your-login-text).setIcon(R.drawable.your-login-icon);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case MENU_ADD: doAddStuff(); break;
case MENU_LIST: doListStuff(); break;
case MENU_REFRESH: doRefreshStuff(); break;
case MENU_LOGIN: doLoginStuff(); break;
}
return false;
}
The following specific example adds a MENU_LOGOUT option if the user is logged in.
private static final int MENU_LOGOUT = MENU.FIRST + 4;
public boolean onPrepareOptionsMenu(Menu menu) {
...
if(auth.isLoggedIn()) {
menu.add(0, MENU_LOGOUT, Menu.NONE, R.string.your-logout-text).setIcon(R.drawable.your-logout-icon);
}
...
}
public boolean onOptionsItemSelected(MenuItem item) {
...
case MENU_LOGOUT:
if(auth.isLoggedIn()) {
doLogout();
} else {
Toast.makeText(this, "You must have somehow been logged out between the time the menu button was pressed and now.", Toast.DURATION_LONG).show();
}
break;
...
}
That's all there is to it.
In my case the menu items are in the ArrayList , - try this Hope it will help u :)
public void onClick(View v)
{
PopupMenu menu = new PopupMenu(DialogCheckBox.this, v);
for (String s : limits) { // "limits" its an arraylist
menu.getMenu().add(s);
}
menu.show();
}
you can call invalidateOptionsMenu() (note:need to use compatability library like actionBarSherlock to access in case you need to support low API versions) , and then update the menu items according to the status.
there you could hide the login action item and show the logout action item.
you might also try update the icon itself but i never tried it.
private void getPopup(final TextView textView, ArrayList<String> arrayList) {
final PopupMenu popupMenu = new PopupMenu(sContext, textView);
for (int i = 0; i < arrayList.size(); i++) {
popupMenu.getMenu().add(arrayList.get(i));
}
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
textView.setText(item.getTitle());
return false;
}
});
popupMenu.show();
}
Simple way to create menu items :
Dynamic_PopUpMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu menu = new PopupMenu(DialogCheckBox.this, v);
menu.getMenu().add("AGIL"); // menus items
menu.getMenu().add("AGILANBU"); // menus items
menu.getMenu().add("AGILarasan");
menu.getMenu().add("Arasan");
menu.show();
}
});
Try this :)
it's so easy
To create the menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
for (int i = 0; i < list.size(); i++) {
menu.add(0, i, 0, "Menu Name").setShortcut('5', 'c');
}
return true;
}
to get the details from clicked menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId(); //to get the selected menu id
String name = item.getTitle(); //to get the selected menu name
return super.onOptionsItemSelected(item);
}

Categories

Resources