Why is ActionBarSherlock not responding? - android

I'm a noob to android and I am using ActionBarSherlock's menu bar to access menus. Everything works fine on android APIs lower than API 11, but for any API 11 and Above the menu bar/menu items are unresponsive. The menu items highlight when I click them, but they don't execute. It's almost as if the menu items have lost their listener is there a setting that I forgot to implement? any help is greatly appreciated.
My Code:
//My Sherlock wrapper
ActionBarSherlock mSherlock = ActionBarSherlock.wrap(this);
//OnCreate
setTheme(R.style.Theme_Sherlock);
mSherlock.setContentView(R.layout.main);
//Menu Methods
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId())
{
case 1: // id from the xml file
Intent i = new Intent("com.bmoney.GSCC.OPTIONS");
startActivity(i);
return true; // we handled the click, dont pass it up the chain
case 2: // id from the xml file
Intent i2 = new Intent("com.bmoney.GSCC.PREFS");
startActivity(i2);
return true;
}
return false;
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
// TODO Auto-generated method stub
return mSherlock.dispatchCreateOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) { //<-- has Sherlock Menu Import
menu.add(0,1,0,"Preferences").setIcon(R.drawable.ic_action_example).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
menu.add(0,2,0,"Help").setIcon(R.drawable.info).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return true;
}

If I had to guess, your import for MenuItem is for android.view.MenuItem, and not the Sherlock equivalent.
If so, I suggest that:
You add #Override to onOptionsItemSelected()
You delete all android.view.* imports, then re-add them as Sherlock ones (e.g., via Ctrl-Shift-O in Eclipse)
You consolidate your two onCreateOptionsMenu() methods, using the one with the Sherlock import

I think the answer is that you need to "return true" when you handle the menu event.
Also, you might find if you restructure your method to the following that you will have an easier time reading and maintaining it.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.options: // id from the xml file
Intent i = new Intent("com.bmoney.GSCC.OPTIONS");
startActivity(i);
return true; // we handled the click, dont pass it up the chain
case R.id.prefs: // id from the xml file
Intent i = new Intent("com.bmoney.GSCC.PREFS");
startActivity(i);
return true;
}
return false;
}

I think you should add an OnMenuItemClickListener to your menu items when you add them in onCreateOptionsMenu. Then add the OnMenuItemSelected method and implement the code you have in onOptionItemSelected in the OnMenuItemSelected method. So you should have...
#Override
public boolean onMenuItemClick(MenuItem item) {
// Code from inside onoptionItemSelected
}

Related

Change attributes of items on an Android Actionbar

I have an Actionbar displayed on my maps fragment to which I have added a zoom-in button. When selected I would like to replace it with a zoom-out button.
When zoom-in is selected the it is obviously pases in to onOptionsItemSelected as the menu item, so it is easy to set it's attributes like this: viewZoomIn.setVisibility(viewZoomIn.GONE); My problem is, how do I get a reference to the zoom-out button on the action bar to set it as as I would like to viewZoomOut.setVisibility(viewZoomOut.VISIBLE);?
I thought I may be able to store the zoom-in and zoom-out views as instance variables and capture them when I inflate the Actionbar, like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
viewZoomIn = findViewById(R.id.zoom_in);
viewZoomOut = findViewById(R.id.zoom_out);
return super.onCreateOptionsMenu(menu);
This does not work.
Any help on getting hold of thes buttons, or advice on a better way of toggling my zoom-in/zoom-out buttons would be appreciated.
It probably shows, but I am pretty new to Java, so it would be preferable is any assistance were communicated in a simple manner.
Thank you.
You have to apply your visibility logic in onPrepareOptionsMenu(Menu) not in onCreateOptionsMenu(Menu) if you want to toggle MenuItem state.
private boolean currentlyZoomedIn;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// called the first time and after each "invalidateOptionsMenu()"
// if tha Activity is in the "zoomedIn" state, the zoomOut button will be visible
menu.findItem(R.id.zoom_in).setVisible(!currentlyZoomedIn);
menu.findItem(R.id.zoom_out).setVisible(currentlyZoomedIn);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.zoom_in:
// do your logic when zoom_in is clicked
currentlyZoomedIn = true;
break;
case R.id.zoom_out:
// do your logic when zoom_out is clicked
currentlyZoomedIn = false;
break;
}
// force the redraw of the menu
invalidateOptionsMenu();
return super.onOptionsItemSelected(item);
}
By the way, I suggest you to use only one button and move your logic only in onOptionsItemSelected(MenuItem) to avoid an instance variable and the call to invalidateOptionsMenu() in a way like this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// zoom_out_in_id is the id for the common button
if (item.getItemId() == R.id.zoom_out_in_id) {
// get the curren title
final CharSequence title = item.getTitle();
// if the current title is the one of zoom_in button, you have to change its infos to zoom_out ones
if (title.equals("zoom_in_title")) {
// do your logic when zoom_in is clicked
item.setIcon(R.drawable.zoom_out_icon);
item.setTitle("zoom_out_title");
} else if (title.equals("zoom_out_title")) {
// do your logic when zoom_out is clicked
item.setIcon(R.drawable.zoom_in_icon);
item.setTitle("zoom_in_title");
}
}
return super.onOptionsItemSelected(item);
}

Displaying menu in all the activities without overriding onCreateOptionsMenu and onOptionsItemSelected each time

While working with my application, I had to come to come across a situation where I supposed to use menu which has to get displayed in entire application when user click menu button. So I used following code in Default activity but then realized that menu is displaying in that activity but not in all.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.del_boy_menu, menu);
//below comented code for changung dynamically
// MenuItem bedMenuItem = menu.findItem(R.id.home);
// bedMenuItem.setTitle("title changed");
// System.out.println("onCreate executed");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
System.out.println("onOptionSelected executed");
switch (item.getItemId()) {
case R.id.home:
// Single menu item is selected do something
// Ex: launching new activity/screen or show alert message
Toast.makeText(MainDeliveryBoyActivity.this, "Home is Selected", Toast.LENGTH_SHORT).show();
// MenuHomeActivity
startActivity(new Intent(context,MenuHomeActivity.class));
return true;
case R.id.delivered1:
Toast.makeText(MainDeliveryBoyActivity.this, "delivered is Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.cancelled:
Toast.makeText(MainDeliveryBoyActivity.this, "cancelled is Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.active:
Toast.makeText(MainDeliveryBoyActivity.this, "active is Selected", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
So my question is should I copy and paste all the above code in all the activities? or is there a way where I can skip this?
Create one global activity called BaseActivity and make all of your activities extend it.
public class BaseActivity extends AppCompatActivity{
public void onCreate(Bundle iCreate){
...
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.del_boy_menu, menu);
....
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
....
}
}
And now all other activities should extend the BaseActivity, so you won't need to write code to inflate menu everytime.
public class Activity1 extends BaseActivity{
....
}
I believe each activity to have a unique menu. But there is a way you can do what you are trying to implement here.
You can create a base class that inherits from an Activity class and put all your menu logic on that base class.
And you can also refer to this answer, Reuse the Action Bar in all the activities of app and this article.
PS: I do not take credit for the answer, I just want to help. Cheers!

how to deal with action bar's button listners

I am new to android and dont know where should i write the actionlistner code for action bar buttons so that i don't need to write the action listner code in all activity.
Please look at below image: i have a menu.xml file for action bar menu and added in one of my activity via onCreateOptionMenu function. when user click on any of my button of action bar then i can track it via onOptionItemSelected function.
Problem-1: For all other activity, i can use same menu.xml file but do i need to override onCreateOptionMenu function of each activity.
Problem 2: Do i need to write onOptionItemSelected function code in all activity?
Please suggest me better solution of these problems.
Problem-1: For all other activity, i can use same menu.xml file but do i need to override onCreateOptionMenu function of each activity.
Problem 2: Do i need to write onOptionItemSelected function code in all activity?
You can create a 'base' Activity and implement the methods in that. Then all you need to do is make sure all other Activities extend the 'base' Activity.
Example (note I use ActionBarSherlock so my 'base' Activity initially extends ShelockFragmentActivity - that may not be the same in your case but this gives an example)...
public class MyBaseFragmentActivity extends SherlockFragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
// Handle menu selection here
}
}
Now any Activity that extends that 'base' Activity will automatically inherit the menu creation and item selection methods of the 'base' class.
public class ActivityA extends MyBaseFragmentActivity {
// No need to create the menu or handle item selection
}
Problem-1: For all other activity, i can use same menu.xml file but do i need to override onCreateOptionMenu function of each activity.
Yes, simply add your code to handle the menu options in a switch statement.
Problem 2: Do i need to write onOptionItemSelected function code in all activity?
Yes, for each activity that is using the action bar, you will need to override the onOptionItemSelected function and add your custom code.
For example:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_watchlist:
Intent intent = new Intent(HomeActivity.this, WatchlistActivity.class);
intent.putExtra("username", currentUser.getUsername());
startActivityForResult(intent, 0);
return true;
case R.id.menu_history:
Intent intent2 = new Intent(HomeActivity.this, HistoryActivity.class);
intent2.putExtra("username", currentUser.getUsername());
startActivityForResult(intent2, 0);
return true;
case R.id.menu_scores:
// Scores only available with Facebook login
if (facebookLogin)
{
Intent scoreIntent = new Intent(HomeActivity.this, ScoresActivity.class);
scoreIntent.putExtra("username", currentUser.getUsername());
scoreIntent.putExtra("accessToken", accessToken);
Session session = Session.getActiveSession();
scoreIntent.putExtra("session", session);
startActivityForResult(scoreIntent, 0);
}
else
Toast.makeText(getApplicationContext(), "Please login to Facebook to use this feature.", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_settings:
Intent intent3 = new Intent(HomeActivity.this, SettingsActivity.class);
intent3.putExtra("username", currentUser.getUsername());
startActivityForResult(intent3, 0);
return true;
default:
return super.onOptionsItemSelected(item);
}

How can I make a menu option expand in android?

I wrote this code in mainactivty.java
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add("About");
return true;
}
It creates a menu, but I want it to open a new window when I click on the menu.
I'm not sure if this is what you want (cause it seems too obvious) but it sounds like you're asking for the following
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.someItem: //this is your menu item in the menu.xml
startActivity(new Intent(this, MyNewActivity.class)); //here you start your new activity
break;
}
}

Deciding the menu's action dynamically

I add menu's in my application dynamically depending on the values i get from the back-end in the onPrepareOptionsMenu(Menu menu). Now i would want to decide the action that is to be performed for the menu added dynamically (as i do not know the action to be performed beforehand) depending on certain values that came associated with the menu from the back-end. How do i achieve this. Kindly provide me some ideas on this. Thanks in advance.
Look into onCreateOptionsMenu and onPrepareOptionsMenu. Basically you need to overwrite them in your Activity and handle menus there. You can either remove or add menus in these overwridden methods.
Whole procedure is well-documented and described here
If you mean the option menu, then this guide should help you: Changing the Menu.
It shows how you can dynamically add and remove items from the menu right before it is shown to the user using the onPrepareOptionsMenu() method, which passes you the menu. You can then add or remove items from the menu.
You have to play around with onPrepareOptionsMenu and onCreateOptionsMenu. Here is good example how to do that.
I found a way to achieve what i wanted. I put the values associated to the menu as a part of the MenuItems intent. In the onOptionsItemSelected(MenuItem item) i get the intent from the MenuItem retrieve the values from it and perform the action required. The code is as below:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
ApplicationManager.getInstance().resetCounter();
menu.removeGroup(1);
Vector listOfMenuToBeAdded=Service.getInstance().getMenuList();
Enumeration<com.data.Menu> menuEnumeration = listOfMenuToBeAdded.elements();
while (menuEnumeration.hasMoreElements()) {
com.data.Menu levelOptions = (com.pravaa.mobile.dashboard.data.Menu) menuEnumeration
.nextElement();
MenuItem levelMenuItem = menu.add(1, 100, Menu.NONE,
levelOptions.getCaption());
LevelOptionIntent levelOptionIntent = new LevelOptionIntent();
levelOptionIntent.setAppCode(levelOptions.getAppCode());
levelOptionIntent.setDashboardNumber(levelOptions.getNumber());
levelOptionIntent.setUniqueRecordId(levelOptions
.getUniqueRecordId());
levelOptionIntent.setLevelNumber(levelOptions.getLevelNo());
levelMenuItem.setIntent(levelOptionIntent);
}
return true;
}
Once a menu item is clicked on perform the action according to the values set in the intent.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case 100:
LevelOptionIntent levelOptionIntent = (LevelOptionIntent) item
.getIntent();
//Perform what you would want to based on the values set in the intent.
if (levelOptionIntent.getAppCode().equals(A)) {
// Start activity A
}elseif (levelOptionIntent.getAppCode().equals(B)) {
// Start activity B
}else if (levelOptionIntent.getAppCode().equals(C)) {
// Start activity C
}
break;
}
return true;
}
The LevelOptionsIntent class is as below:
public class LevelOptionIntent extends Intent {
private int dashboardNumber;
private String appCode;
private String uniqueRecordId;
private int levelNumber;
public LevelOptionIntent() {
super();
// TODO Auto-generated constructor stub
}
public int getDashboardNumber() {
return dashboardNumber;
}
public void setDashboardNumber(int dashboardNumber) {
this.dashboardNumber = dashboardNumber;
}
public String getAppCode() {
return appCode;
}
public void setAppCode(String appCode) {
this.appCode = appCode;
}
public String getUniqueRecordId() {
return uniqueRecordId;
}
public void setUniqueRecordId(String uniqueRecordId) {
this.uniqueRecordId = uniqueRecordId;
}
public int getLevelNumber() {
return levelNumber;
}
public void setLevelNumber(int levelNumber) {
this.levelNumber = levelNumber;
}}
I am not sure if this is the right way of doing it though.Can someone throw some light on this.
Thanks in advance.

Categories

Resources