how to deal with action bar's button listners - android

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

Related

Android oncreateOption menu for reload a activity

I have Activity with Action Which have a refresh icon in OnCreateOption Menu.I want to reload my current Activity On click this Icon Click.But I don't know to use here click event.How to resolve this.
Override onOptionsItemSelected method like this way:
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
Intent intent = new Intent();
switch (item.getItemId()) {
case R.id.mnuRefresh: // your menu item id
reCreate();
break;
}
return false;
}
There is a good example here :
https://stackoverflow.com/a/7480103/2724418

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!

Why is ActionBarSherlock not responding?

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
}

How to call Activity from a menu item in Android?

I'm attempting to call startActivity(myIntent) from the click of a menu button but my application crashes at that point.
The same startActivity call works fine from a regular button click, so, I assume the menu button is missing information about the context? Or maybe I'm totally off the mark here.
So... what's the correct way to have a menu item take me to a specific Activity?
I've revised my code based on the initial set of advice. Still crashing in the same place. The debugger doesn't enter the exception clause, the app just dies.
[EDITED WITH CODE SNIPPET]
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
try{
switch (item.getItemId()) {
case R.id.menuItemLang:
startActivity(new Intent("com.my.project.SETTINGS"));
return true;
default:
return super.onOptionsItemSelected(item);
}
}catch(Exception e){
log(e);
}
}
First option
You have to override onOptionsItemSelected method in your Activity, which is called when user clicks on the item in Options menu. In the method you can check what item has been clicked.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_item1:
Intent intent = new Intent(this, ActivityForItemOne.class);
this.startActivity(intent);
break;
case R.id.menu_item2:
// another startActivity, this is for item with id "menu_item2"
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
There is also onContextItemSelected method which works similary, but for Context menu (I'm not sure, what menu you mean).
More information at http://developer.android.com/guide/topics/ui/menus.html
EDIT:
Second option
I think the first option is easier, but from your code I see, that you want to start activity as an action (because of String parameter in Intent constructor). To do this, you need to specify an action in your AndroidManifest.xml. So, if I would start activity ActivityForItemOne (from previous example) the <application> element in AndroidManifest.xml would look like this:
<application ...>
...
<activity android:label="Activity For First Item" android:name=".ActivityForItemOne">
<intent-filter>
<action android:name="my.app.ITEMONE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
And the Intent will be:
Intent intent = new Intent("my.app.ITEMONE");
The my.app. is package of your application. It's not necessary to use your application package, but it's recommended for uniqueness of actions.
More information at:
Class Intent - Action and Category constants
Action element
Intents and Intent Filters
Hope this solve your problem.
More optimice:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
return true;
case R.id.item2:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
if There have 2 Class
1 MainActivity
2 Welcome
then you need to go from
welcom>MainActivity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.logout:
Intent intent = new Intent(this, MainActivity.class);
this.startActivity(intent);
break;
case R.id.settings:
// another startActivity, this is for item with id "menu_item2"
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}

Same Title Bar but different View below it in Android?

In one of my Android Application I need to keep the title bar same but the view that is shown in the rest of the screen changes. So, I have taken different Activity for all the views that I need to show and set the title bar in every Activities onCreate method.
Now, the problem is that I have a button in the title bar and need to perform certain action on its click event. Writing the same event handling code in every Activity class is very cumbersome. Is there any other way out that whenever there is a click event on that button of the title bar then we can have the same functionality without writing the same code in all the Activity classes.
Can we use ViewGroup for that? I don't have much idea about ViewGroup. Is that possible with ViewGroup?
If anyone knows the solution then please let me know.
Thanks & Regards
Sunil
If you are sharing view elements and functionality amongst several classes extending Activity, you might want to consider making a common superclass to handle this overlap.
The best solution is to keep a base activity like this.
public class HeaderBaseActivity extends AppCompatActivity{
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
mAppPreferences = AppUtil.getAppPreferences(this);
item_patients = menu.findItem(R.id.item_patients);
setBatchCountOnMenu(0);
RealmConfiguration realmConfig = new RealmConfiguration.Builder(this).build();
mRealm = Realm.getInstance(realmConfig);
mDotor = new Gson().fromJson(mAppPreferences.getString(Constants.SETTINGS_OBJ_DOCTOR, ""), Doctor.class);
mAppPreferences = AppUtil.getAppPreferences(this);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_logout:
/* DialogUtility.showShortToast(this, " Main manu Action Logout");*/
SharedPreferences.Editor Editor = mAppPreferences.edit();
Editor.putBoolean(Constants.SETTINGS_IS_LOGGED_IN, false);
Editor.apply();
clearRealmDB();
Intent loginIntent = new Intent(HeaderBaseActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(loginIntent);
finish();
break;
case R.id.item_patients:
System.out.println("current activity "+getApplicationContext());
Intent mPatientListIntent = new Intent(HeaderBaseActivity.this, PatientSummaryInfoActivity.class);
mPatientListIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mPatientListIntent);
break;
case R.id.action_doctor_profile:
openDialogOfDoctorProfile();
break;
}
return super.onOptionsItemSelected(item);
}
}
Your other activities can extend the above activity like this:
public class MainActivity extends HeaderBaseActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
}
}

Categories

Resources