I got a sub-menu that I add with values, I then want to set them up by reading the currentViewMode variable that contain the current view mode... The code below must check the first one but it doesn't. Please advise.
private enum ViewMode
{
NORMAL,
SATELLITE,
HYBRID
}
private ViewMode currentViewMode = ViewMode.NORMAL;
private final int SUB_MENU_GROUP = 1;
private final int SUB_MENU_ITEM_NORMAL = 1;
private final int SUB_MENU_ITEM_SATELLITE = 2;
private final int SUB_MENU_ITEM_HYBRID = 3;
public boolean onCreateOptionsMenu(Menu menu) {
SubMenu sub = menu.addSubMenu(0, 1, 0, R.string.menu_mapwindow_viewmode).setIcon(R.drawable.ic_menu_refresh);
sub.add(SUB_MENU_GROUP, SUB_MENU_ITEM_NORMAL, Menu.NONE, this.getString(R.string.mapwindow_viewmode_normal));
sub.add(SUB_MENU_GROUP, SUB_MENU_ITEM_SATELLITE, Menu.NONE, this.getString(R.string.mapwindow_viewmode_satellite));
sub.add(SUB_MENU_GROUP, SUB_MENU_ITEM_HYBRID, Menu.NONE, this.getString(R.string.mapwindow_viewmode_hybrid));
sub.setGroupCheckable(SUB_MENU_GROUP, true, true);
if (this.currentViewMode == ViewMode.NORMAL)
sub.findItem(SUB_MENU_ITEM_NORMAL).setChecked(true);
else if (this.currentViewMode == ViewMode.SATELLITE)
sub.findItem(SUB_MENU_ITEM_SATELLITE).setChecked(true);
else if (this.currentViewMode == ViewMode.HYBRID)
sub.findItem(SUB_MENU_ITEM_HYBRID).setChecked(true);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case SUB_MENU_ITEM_NORMAL:
item.setChecked(!item.isChecked());
this.currentViewMode = ViewMode.NORMAL;
Log.i(this.getClass().getName(), "Normal");
break;
case SUB_MENU_ITEM_SATELLITE:
item.setChecked(!item.isChecked());
this.currentViewMode = ViewMode.SATELLITE;
Log.i(this.getClass().getName(), "Satellite");
break;
case SUB_MENU_ITEM_HYBRID:
item.setChecked(!item.isChecked());
this.currentViewMode = ViewMode.HYBRID;
Log.i(this.getClass().getName(), "Hybrid");
break;
default:
super.onOptionsItemSelected(item);
}
return true;
}
You should make the checkbox updates in onPrepareOptionsMenu (instead of onCreateOptionsMenu), as it will be invoked on every menu open.
Create only called before the very first.
(its not sure if this is causing your problem, but is possible, so worth a try, and makes your code safer, anyway)
Related
Android has new ui element - BottomNavigationView
I don't want to contain my menus in the xml files. I will receive the information about menu items and order from backend side. I want to create them dynamically and set into the BottomNavigationView in the onCreate() method. Can I do this?
By default, BottomNavigationView starts with an empty menu. You can use the getMenu() method to get the Menu instance, then add menu items as in the response above. For example,
BottomNavigationView bottomNavigation = findViewById(R.id.bottom_navigation);
Menu menu = bottomNavigation.getMenu();
menu.add(Menu.NONE, MENU_ITEM_ID_ONE, Menu.NONE, getString(R.string.str_menu_one))
.setIcon(R.drawable.ic_action_one);
The easy way to use dynamic options in bottom navigation view is use different menu items like this:
switch (userType){
case UserTypes.A:
bottomNavigationView.inflateMenu(R.menu.menu_bottom_navigation_a);
break;
case UserTypes.B:
bottomNavigationView.inflateMenu(R.menu.menu_bottom_navigation_b);
break;
case UserTypes.C:
bottomNavigationView.inflateMenu(R.menu.menu_bottom_navigation_c);
break;
}
Heres an example of dynamic build of menu items, in the main activity u have 2 layouts.
you can get your own layout from your backend and create menu items dynamically using menu.add
src: http://www.mobiledevguide.com/2014/01/dynamically-create-menu-items-in-android.html
public class MainActivity extends Activity {
private Button mButtonOne,mButtonTwo;
private static final int MENU_ITEM_ID_ONE =1;
private static final int MENU_ITEM_ID_TWO =2;
private static final int MENU_ITEM_ID_THREE =3;
private static final int MENU_ITEM_ID_FOUR =4;
private static final int MENU_ITEM_ID_FIVE =5;
private static final int MENU_ITEM_ID_SIX =6;
private int mMenuSet = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonOne=(Button) findViewById(R.id.buttonSetOne);
mButtonTwo=(Button) findViewById(R.id.buttonSetTwo);
mButtonOne.setOnClickListener(clickListener);
mButtonTwo.setOnClickListener(clickListener);
}
OnClickListener clickListener=new OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId()==R.id.buttonSetOne) {
mMenuSet=1;
} else if (v.getId()==R.id.buttonSetTwo){
mMenuSet=2;
}
invalidateOptionsMenu();
/*
* if you are using ActionBarSherlock use this.supportInvalidateOptionsMenu();
* if you are using ActionBarCompat use invalidateOptionsMenu (Activity activity) method
* */
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
if(mMenuSet==1){
menu.add(Menu.NONE, MENU_ITEM_ID_ONE, Menu.NONE,getString(R.string.str_menu_one)).setIcon(R.drawable.ic_action_one).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
menu.add(Menu.NONE, MENU_ITEM_ID_TWO, Menu.NONE,getString(R.string.str_menu_two)).setIcon(R.drawable.ic_action_two).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
menu.add(Menu.NONE, MENU_ITEM_ID_THREE, Menu.NONE,getString(R.string.str_menu_three)).setIcon(R.drawable.ic_action_three);
}else if(mMenuSet==2){
menu.add(Menu.NONE, MENU_ITEM_ID_FOUR, Menu.NONE,getString(R.string.str_menu_four)).setIcon(R.drawable.ic_action_four).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
menu.add(Menu.NONE, MENU_ITEM_ID_FIVE, Menu.NONE,getString(R.string.str_menu_five)).setIcon(R.drawable.ic_action_five).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
menu.add(Menu.NONE, MENU_ITEM_ID_SIX, Menu.NONE,getString(R.string.str_menu_six)).setIcon(R.drawable.ic_action_six);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ITEM_ID_ONE:
Toast.makeText(this, "Click on "+ getString(R.string.str_menu_one), Toast.LENGTH_SHORT).show();
break;
case MENU_ITEM_ID_TWO:
Toast.makeText(this, "Click on "+ getString(R.string.str_menu_two), Toast.LENGTH_SHORT).show();
break;
case MENU_ITEM_ID_THREE:
Toast.makeText(this, "Click on "+ getString(R.string.str_menu_three), Toast.LENGTH_SHORT).show();
break;
case MENU_ITEM_ID_FOUR:
Toast.makeText(this, "Click on "+ getString(R.string.str_menu_four), Toast.LENGTH_SHORT).show();
break;
case MENU_ITEM_ID_FIVE:
Toast.makeText(this, "Click on "+ getString(R.string.str_menu_five), Toast.LENGTH_SHORT).show();
break;
case MENU_ITEM_ID_SIX:
Toast.makeText(this, "Click on "+ getString(R.string.str_menu_six), Toast.LENGTH_SHORT).show();
break;
case R.id.action_settings:
Toast.makeText(this, "Click on "+ getString(R.string.action_settings), Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}}
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);
}
Im trying to do something like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
//multiListener = false;
menu.add(0,START_DELETE,0, "Delete selected..").setEnabled(multiListener);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.multiselect:
if(multiselect == 0) { multiselect = 1;
multiListener = true;
Log.d("DH", "index="+multiListener);
}
else if(multiselect == 1) { multiselect = 0; multiListener = false;
Log.d("DH", "index="+multiListener);
}
fillData();
return true;
case START_DELETE:
Toast.makeText(Notepadv3.this, "Pressed delete", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Basically, if multiListener = true; make "Delete selected.." pressable otherwise gray it out...
This simple , thing.. doesn't want to work out with me,
for somehow... the button is always greyed out, although Log says that, it changes to true...
Anyone, know something?
You should call setEnabled() again to change item's state. Its state doesn't bind to a variable. This method should be called in onPrepareOptionsMenu().
I'm trying to figure out how to include common pieces of code in multiple activities.
More specifically, I have a context menu that I would like to include in several activities.
I saw this, but just don't understand how to extend to multiple activities.
http://developer.android.com/guide/topics/ui/menus.html
I have this set up as Menu.java
public class Menu extends Activity{
// bottom menus
public static final int Menu1 = 1;
public static final int Menu2 = 2;
public static final int Menu3 = 3;
public static final int Menu4 = 4;
public static final int Menu5 = 5;
public static final int Menu6 = 6;
public static final int Menu7 = 7;
// / Creates the menu items
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, Menu3, 0, "Create Profile").setIcon(
this.getResources().getDrawable(R.drawable.ic_menu_add));
menu.add(0, Menu5, 0, "Log In").setIcon(
this.getResources().getDrawable(R.drawable.ic_menu_login));
menu.add(0, Menu2, 0, "Settings").setIcon(
this.getResources().getDrawable(R.drawable.ic_menu_preferences));
menu.add(0, Menu4, 0, "About").setIcon(
this.getResources().getDrawable(R.drawable.ic_menu_help));
menu.add(0, Menu1, 0, "Report A Bug").setIcon(
this.getResources().getDrawable(R.drawable.ic_menu_start_conversation));
menu.add(0, Menu6, 0, "New Stuff").setIcon(
this.getResources().getDrawable(R.drawable.ic_menu_view));
return true;
}
private MenuItem add(int i, int menu32, int j, String string) {
// TODO Auto-generated method stub
return null;
}
// Handles item selections from preference menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case Menu1:
startActivity(new Intent(this, Bug.class));
return true;
case Menu2:
startActivity(new Intent(this, EditPreferences.class));
return true;
case Menu3:
startActivity(new Intent(this, CreateAccount.class));
return true;
case Menu4:
startActivity(new Intent(this, About.class));
return true;
case Menu5:
startActivity(new Intent(this, Login.class));
return true;
case Menu6:
startActivity(new Intent(this, NewAdditions.class));
return true;
}
return false;
}
}
if you want to add same functionality in more than 1 activity than create 1 common activity
like BaseActivity and extend that activity will include that common functions in your inherited all activities
for example i have called checklogin function , you can put your menu code here,
public class BaseActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settings = getSharedPreferences(PREFS_NAME, 0);
if (IsFullScreen) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
this.CheckLogin();
}
// Check login function
// Your menu code
}
now you can extend it in your activities
public class MainScreen extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.mainscreen);
}
}
You can define a menu in an xml file and then load the menu in onCreateOptionsMenu. You will still need to handle each menu item in each activity. You could also create a BaseActivity class that handles the menu stuff that each Activity could extend.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/about" android:title="About"
android:icon="#drawable/ic_menu_about"/>
<item android:id="#+id/search"
android:icon="#drawable/ic_menu_search" android:title="Search"></item>
<item android:id="#+id/my_location"
android:title="My Location"
android:icon="#drawable/ic_menu_mylocation">
</item>
</menu>
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return super.onCreateOptionsMenu(menu);
}
Try to use a abstract class
abstract class BaseMenu extends Activity
{
//Initialize your menus
// bottom menus
public static final int Menu1 = 1;
public static final int Menu2 = 2;
public static final int Menu3 = 3;
public static final int Menu4 = 4;
public static final int Menu5 = 5;
public static final int Menu6 = 6;
public static final int Menu7 = 7;
// / Creates the menu items
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, Menu3, 0, "Create Profile").setIcon(
this.getResources().getDrawable(R.drawable.ic_menu_add));
menu.add(0, Menu5, 0, "Log In").setIcon(
this.getResources().getDrawable(R.drawable.ic_menu_login));
menu.add(0, Menu2, 0, "Settings").setIcon(
this.getResources().getDrawable(R.drawable.ic_menu_preferences));
menu.add(0, Menu4, 0, "About").setIcon(
this.getResources().getDrawable(R.drawable.ic_menu_help));
menu.add(0, Menu1, 0, "Report A Bug").setIcon(
this.getResources().getDrawable(R.drawable.ic_menu_start_conversation));
menu.add(0, Menu6, 0, "New Stuff").setIcon(
this.getResources().getDrawable(R.drawable.ic_menu_view));
return true;
}
private MenuItem add(int i, int menu32, int j, String string) {
// TODO Auto-generated method stub
return null;
}
// Handles item selections from preference menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case Menu1:
startActivity(new Intent(this, Bug.class));
return true;
case Menu2:
startActivity(new Intent(this, EditPreferences.class));
return true;
case Menu3:
startActivity(new Intent(this, CreateAccount.class));
return true;
case Menu4:
startActivity(new Intent(this, About.class));
return true;
case Menu5:
startActivity(new Intent(this, Login.class));
return true;
case Menu6:
startActivity(new Intent(this, NewAdditions.class));
return true;
}
return false;
}}
Now extend the class BaseMenu instead of Activity
I Think this could help you out.
can any one guide me how to add some menu related buttons at the bottom of each activity?
Do you mean the Options Menu?
If so, you'll need to add some code like this to your Activity:
private static final int MENU_SEARCH = Menu.FIRST;
private static final int MENU_PREFERENCES = Menu.FIRST + 1;
private static final int MENU_HELP = Menu.FIRST + 2;
/* Creates the menu items */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, MENU_SEARCH, Menu.NONE, "Search")
.setIcon(android.R.drawable.ic_menu_search);
menu.add(Menu.NONE, MENU_PREFERENCES, Menu.NONE, "Preferences")
.setIcon(android.R.drawable.ic_menu_preferences);
menu.add(Menu.NONE, MENU_HELP, Menu.NONE, "Help")
.setIcon(android.R.drawable.ic_menu_help);
return true;
}
/* Handles item selections */
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SEARCH:
search();
return true;
case MENU_PREFERENCES:
preferences();
return true;
case MENU_HELP:
showHelp();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
Note that Menu.add() returns the MenuItem created so you can chain the call to setIcon().