Checkbox item state on menu android - android

How can I set initial value of checkbox item part of a menu? When I start an Activity I want to set a boolean value saved in Shared Preferences.
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".LoginActivity">
<item
android:id="#+id/checkbox"
android:title="#string/checkbox"
android:orderInCategory="10"
android:showAsAction="never"
android:visible="true"
android:checkable="true"
android:checked="true"/>
</menu>
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.checkbox){
if(item.isChecked()){
item.setChecked(false);
}else{
item.setChecked(true);
}
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(PrefsConsts.CHECKBOX,item.isChecked());
editor.commit();
}
return true;
}
I can always know what was the value, but I donĀ“t know how to set the new one.

First of all, get rid of the checked value in the layout
<item
android:id="#+id/action_check"
android:title="#string/action_check"
android:orderInCategory="200"
app:showAsAction="never"
android:visible="true"
android:checkable="true"/>
Now you can set it in the code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
SharedPreferences settings = getSharedPreferences("settings", 0);
boolean isChecked = settings.getBoolean("checkbox", false);
MenuItem item = menu.findItem(R.id.action_check);
item.setChecked(isChecked);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_check) {
item.setChecked(!item.isChecked());
SharedPreferences settings = getSharedPreferences("settings", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("checkbox", item.isChecked());
editor.commit();
return true;
}
return super.onOptionsItemSelected(item);
}

Related

Make menu item on android work like a button

I'm here to see if they guide me in this problem
I have a menu, with an item, and what I want is that item to work as a button, if you click on it change the icon and a toast that says Notification active, and if you click again, change the icon and say using toast, Disabled notifications.
All this I have achieved, the detail is that when activating the button and leaving the activity and when entering again, the button is again deactivated, when it should be activated
I hope you understand, here I give you the code, which makes the function perfect, but I think I must do something with shared preferences to save if it is clicked or not, but I do not know where to start, I hope you understand and guide me, I leave the code that I have implemented
----- xml menu ------------
<?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:icon="#drawable/ic_notifications_off_black_24dp"
android:title="#string/notificaciones"
android:id="#+id/notificaciones"
android:checkable="true"
app:showAsAction="always"
/>
</menu>
--------- Java---------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menucampeonatos, menu);
MenuItem item = menu.findItem(R.id.notificaciones);
item.setChecked(false);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem checkable = menu.findItem(R.id.notificaciones);
checkable.setChecked(false);
return super.onPrepareOptionsMenu(menu);
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.notificaciones:
if (item.isChecked()){
myRef.update("notificacion", false);
item.setChecked(false);
item.setIcon(R.drawable.ic_notifications_off_black_24dp);
Toast.makeText(this, "Notificaciones Desactivadas para este campeonato", Toast.LENGTH_LONG).show();
}else{
myRef.update("notificacion", true);
item.setChecked(true);
item.setIcon(R.drawable.ic_notifications_active_black_24dp);
Toast.makeText(this, "Notificaciones Activadas para este campeonato", Toast.LENGTH_LONG).show();
}
return true;
}
return super.onOptionsItemSelected(item);
}
First you need to implement Shared Preferences, as you mentioned
private String sharedPrefFile = "your Shared Preferences Name";
private String NOTIFICATION_KEY = "notification_key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPreferences = getSharedPreferences(sharedPrefFile, MODE_PRIVATE);
...
}
Then, in your onOptionsItemSelected, you need to save user action to preference
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.notificaciones:
if (item.isChecked()){
// Add this line
SharedPreferences.Editor preferencesEditor = mPreferences.edit();
preferencesEditor.putBoolean(NOTIFICATION_KEY, true);
preferencesEditor.apply();
myRef.update("notificacion", false);
item.setChecked(false);
item.setIcon(R.drawable.ic_notifications_off_black_24dp);
Toast.makeText(this, "Notificaciones Desactivadas para este campeonato", Toast.LENGTH_LONG).show();
}else{
// Add this line
SharedPreferences.Editor preferencesEditor = mPreferences.edit();
preferencesEditor.putBoolean(NOTIFICATION_KEY, false);
preferencesEditor.apply();
myRef.update("notificacion", true);
item.setChecked(true);
item.setIcon(R.drawable.ic_notifications_active_black_24dp);
Toast.makeText(this, "Notificaciones Activadas para este campeonato", Toast.LENGTH_LONG).show();
}
return true;
}
return super.onOptionsItemSelected(item);
}
Lastly, load the preference everytime activity is destroyed in onPrepareOptionsMenu
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem checkable = menu.findItem(R.id.notificaciones);
String isNotificationClicked = mPreferences.getBoolean(NOTIFICATION_KEY, false);
checkable.setChecked(isNotificationClicked);
return super.onPrepareOptionsMenu(menu);
}

Multiple selection on menu checkbox

I'm trying to create a menu with filters on a map, the idea is to select multiple elements (like the screenshoot). But the problem is that every time I press an option, the menu is automatically hidden.
So I can only tap one checkbox everytime I open the menu. This behaviour is not the best because user has to open N times the menu to select N filters.
Any suggestion or advice about how to solve this? Thanks!
And this is my code (reduced to be more readable):
map_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_filtro"
app:showAsAction="always" >
<menu>
<group android:checkableBehavior="all">
<item
android:id="#+id/nav_ciencia"
android:icon="#drawable/ciencia"
android:title="#string/filtro_ciencia"
app:showAsAction="never"
/>
<item
android:id="#+id/nav_comercio"
android:icon="#drawable/comercio"
android:title="#string/filtro_comercio"
app:showAsAction="never"
/>
<item
android:id="#+id/nav_cultura"
android:icon="#drawable/cultura"
android:title="#string/filtro_cultura"
app:showAsAction="never"
/>
<item
android:id="#+id/nav_deporte"
android:icon="#drawable/deporte"
android:title="#string/filtro_deportes"
app:showAsAction="never"
/>
</group>
</menu>
</item>
</menu>
Activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map_drawer, menu);
SharedPreferences prefs = getSharedPreferences(Constants.pref_name, Context.MODE_PRIVATE);
MenuItem item_ciencia = menu.findItem(R.id.nav_ciencia);
item_ciencia.setChecked(prefs.getBoolean(Constants.pref_nav_ciencia, false));
MenuItem item_comercio = menu.findItem(R.id.nav_comercio);
item_comercio.setChecked(prefs.getBoolean(Constants.pref_nav_comercio, false));
MenuItem item_cultura = menu.findItem(R.id.nav_cultura);
item_cultura.setChecked(prefs.getBoolean(Constants.pref_nav_cultura, false));
MenuItem item_deporte = menu.findItem(R.id.nav_deporte);
item_deporte.setChecked(prefs.getBoolean(Constants.pref_nav_deporte, false));
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
SharedPreferences prefs = getSharedPreferences(Constants.pref_name, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
if (id == R.id.action_settings) {
return true;
}else if (id == R.id.nav_ciencia) {
item.setChecked(!item.isChecked());
editor.putBoolean(Constants.pref_nav_ciencia, item.isChecked());
editor.commit();
return true;
} else if (id == R.id.nav_comercio) {
item.setChecked(!item.isChecked());
editor.putBoolean(Constants.pref_nav_comercio, item.isChecked());
editor.commit();
return true;
} else if (id == R.id.nav_cultura) {
item.setChecked(!item.isChecked());
editor.putBoolean(Constants.pref_nav_cultura, item.isChecked());
editor.commit();
return true;
} else if (id == R.id.nav_deporte) {
item.setChecked(!item.isChecked());
editor.putBoolean(Constants.pref_nav_deporte, item.isChecked());
editor.commit();
return true;
}
return super.onOptionsItemSelected(item);
}

Save optionMenu item icon to shared preferences

I have a list of data with two different views in my Fragment, my default view is Listview and another is Gridview. I switch between this two views by clicking on an icon on my toolbar.
And I set the switch item icon dynamically inside onOptionsItemSelected method like this:
//global variables
private int currentViewMode = 0 ;
static final int VIEW_MODE_LISTVIEW = 0;
static final int VIEW_MODE_GRIDVIEW = 1;
.
.
.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.switchView:
if (VIEW_MODE_LISTVIEW == currentViewMode){
item.setIcon(R.mipmap.ic_gridview);
currentViewMode = VIEW_MODE_GRIDVIEW;
}else {
item.setIcon(R.mipmap.ic_listview);
currentViewMode = VIEW_MODE_LISTVIEW;
}
switchView();
SharedPreferences sharedPreferences = activity.getSharedPreferences("ViewMode",currentViewMode);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("currentViewMode",currentViewMode);
editor.commit();
return false;
default:
break;
}
return super.onOptionsItemSelected(item);
}
And I get my view from shared preferences like this:
SharedPreferences sharedPreferences = activity.getSharedPreferences("ViewMode",activity.MODE_PRIVATE);
currentViewMode = sharedPreferences.getInt("currentViewMode",VIEW_MODE_LISTVIEW);
But I don't know how can I save the item icon and how to retrive it.
Can you help me please?
Menu
<?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/switchView"
android:title=""
android:icon="#mipmap/ic_listview"
app:showAsAction="always"/>
</menu>
You can add another item inside your menu.xml for your gridView Then create a boolean that carries the visibility of this two items. when you switch to listview, set the visibility of gridItem to false, And when you switch to gridview, set the listItem to false; In this way you'll be able to save and retrieve the visibilities with shared preferences as a boolean.
Change your code like this:
<item
android:id="#+id/switchListView"
android:title=""
android:icon="#mipmap/ic_listview"
app:showAsAction="always"/>
<item
android:id="#+id/switchGridView"
android:title=""
android:icon="#mipmap/ic_gridview"
android:visible="false"
app:showAsAction="always"/>
Inside your Fragment:
boolean isGridView;
Then:
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(activity);
isGridView = myPrefs.getBoolean("menu_item", false);
And finally change your onOptionItemSelected method like this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(activity);
final SharedPreferences.Editor editor = myPrefs.edit();
isGridView = myPrefs.getBoolean("menu_item", false);
switch (item.getItemId()) {
case R.id.switchListView:
if (VIEW_MODE_LISTVIEW == currentViewMode){
isGridView=true;
editor.putBoolean("menu_item", isGridView);
editor.commit();
activity.invalidateOptionsMenu();
item.setIcon(R.mipmap.ic_gridview);
currentViewMode = VIEW_MODE_GRIDVIEW;
}else {
isGridView=false;
editor.putBoolean("menu_item", isGridView);
editor.commit();
activity.invalidateOptionsMenu();
item.setIcon(R.mipmap.ic_listview);
currentViewMode = VIEW_MODE_LISTVIEW;
}
switchView();
SharedPreferences sharedPreferences = activity.getSharedPreferences("ViewMode",currentViewMode);
SharedPreferences.Editor et = sharedPreferences.edit();
et.putInt("currentViewMode",currentViewMode);
et.commit();
return false;
case R.id.switchGridView:
if (VIEW_MODE_LISTVIEW == currentViewMode){
isGridView=true;
editor.putBoolean("menu_item", isGridView);
editor.commit();
activity.invalidateOptionsMenu();
item.setIcon(R.mipmap.ic_gridview);
currentViewMode = VIEW_MODE_GRIDVIEW;
}else {
isGridView=false;
editor.putBoolean("menu_item", isGridView);
editor.commit();
activity.invalidateOptionsMenu();
item.setIcon(R.mipmap.ic_listview);
currentViewMode = VIEW_MODE_LISTVIEW;
}
switchView();
sharedPreferences = activity.getSharedPreferences("ViewMode",currentViewMode);
et = sharedPreferences.edit();
et.putInt("currentViewMode",currentViewMode);
et.commit();
return false;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
if(isGridView==true){
menu.findItem(R.id.switchListView).setVisible(false);
menu.findItem(R.id.switchGridView).setVisible(true);
}else{
menu.findItem(R.id.switchListView).setVisible(true);
menu.findItem(R.id.switchGridView).setVisible(false);
}
super.onPrepareOptionsMenu(menu);
}
Important note
How to implement optionMenu inside Fragments:
1. If you have implemented optionMenu inside your MainActivity, then you should return false in your MainActivity's onOptionsItemSelected, otherwise your Fragment's optionMenu will not work.
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
//
}
return false;
}
2. you have to setHasOptionsMenu(true); inside your onCreate in your Fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}

How to save instance state of selected radiobutton on menu

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;
}

How to create preferences in Android?

I have a problem with android settings. I want to create settings for changing the background color of an activity. What do I have to do?
I have layout:
public class MyApp extends PreferenceActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void display(View view)
{
Intent intent = new Intent(this, Display.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected( MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_about:
Intent menu_about = new Intent(this, About.class);
startActivity(menu_about);
return true;
case R.id.menu_copyright:
Intent menu_copyright = new Intent(this, Copyright.class);
startActivity(menu_copyright);
return true;
case R.id.menu_settings:
// ACTIVITY OF SETTINGS
return true;
case R.id.menu_exit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
};
}
I want preference like this:
http://i.stack.imgur.com/k2qA5.png
Now, did You understend me?
Create SharedPreferences this way
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("PrefName", VALUE);
editor.commit();
Get its values this way
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String s = settings.getString("PrefName", ""));
The last statement means you are looking for the value of "PrefName" and setting "" if nothing is found.
Hope it helps
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/settings"
android:title="Settings"
>
<menu>
<item android:id="#+id/red"
android:title="Red" />
<item android:id="#+id/Blue"
android:title="Blue" />
</menu>
</item>
</menu>
AndroidMenusActivity.java
public class AndroidMenusActivity extends Activity {
LinearLayout li;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
li= findViewById(R.id.layoutid);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.red:
li.setBackgroundColor("#ff0000");
break;
case R.id.blue:
li.setBackgroundColor("#0000ff");
break;
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layoutid"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</LinearLayout>
Did you mean Change the activity background over XML file?
android:background="#android:color/xxxxx"
Pick one of listed color.

Categories

Resources