Android: How to show menu only in specific activities? - android

I've many activities in my project and one activity for Login but I want that only show menu in all activities except in activity login, because in that menu will be an icon of end session and when press, return to the login activity. And not how, could you help me?

I would recommend that the layout for login does not have the menu and the layout of other activities if the menu has

Better to an base activity which contains your code for menus and then you can extend it your activities instead of activity.
And for login you can extend activity. so all the activities which extend baseactivity will be reflected with menu with out need to write menus code in every activity. and for the will be no menu as it does not extend base activity.
Updated:::
public class BaseActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
/* Creates the menu items */
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
/* Handles item selections */
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.menu1:
//your stuff
break;
case R.id.menu2:
//your stuff
break;
}
return true;
}
}

Related

LayoutInflater Onclick Not working

I have 2 xml one main xml and one menu xml. I want to get the click event from menu xml to main xml activity. is there is any way to solve this problem.
Main Home Page
Menu Page
Now click on the menu page button event i want in my main home activity page.
I done Like this
View otherLayout = LayoutInflater.from(this).inflate(R.layout.menu_layout,null);
Button tstclick = (Button) otherLayout.findViewById(R.id.textclick);
tstclick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Your thing
System.exit(0);
}
});
The Activity class provides us two methods to inflate/show menu items and work with them or assign some tasks to them. They are:
onCreateOptionsMenu(Menu menu)
onOptionsItemSelected(MenuItem item)
The onCreateOptionsMenu() method is responsible for creating and inflating the menu by help of MenuInflater class.
The onOptionsItemSelected() method is responsible for assigning tasks to each menu item. Each menu item is identified by help of its unique ID.
In order to show and work with menu's in any Activity, both the methods needs to be overridden as shown below:
public class MainActivity extends AppCompatActivity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
// All your menu items will come here. Each menu item ID will become a separate case in the Switch case
default:
return super.onOptionsItemSelected(menuItem);
}
}
}
As soon as the user clicks or taps on any menu item, the onOptionsItemSelected() method is called by the Android OS and then the ID for that particular menu item will be matched in the method. The group of statements specified in the respective case will then be executed.
For more info visit the following links:
http://developer.android.com/guide/topics/ui/menus.html
http://developer.android.com/reference/android/view/MenuInflater.html

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!

Interaction between Activity and Fragments

In my application the main activity hosts two fragments and attached to acticity as ActionBarTabs. using the following code. NOTE: activity and the 2 fragments are defined in seperate xml layout files (See the picture at the bottom)
private void createActionTabs() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//Status Tab
String strStatus = getResources().getString(R.string.lblStatus);
ActionBar.Tab statusTab = actionBar.newTab();
statusTab.setText(strStatus);
TabListener<SFrag> sFTabListener = new TabListener<SFrag>(this, strStatus, SFrag.class);
statusTab.setTabListener(sFTabListener);
actionBar.addTab(statusTab);
//Controller Tab attached the same way
.....
}
The ActionBar Items (start and refresh) are added using
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
Now coming to my problem:
I want to update the data shown on the Status Fragment at application load, fragment resume and click of refresh menu item from the action bar. Now when I try to access the Status fragment from Main Activity using the following code
SFrag frag = (SFrag) getFragmentManager().findFragmentById(R.id.st_frag);
Log.d(TAG, "In Activity SFrag is " + (frag == null ? "null" : "not null"));
if (frag != null) {
//calls the method to update data
fragment.updateStatusData(statusInformation);
}
The getFragmentManager().findFragmentById methods always returns null. I even tried the onResume method of the activity, the fragment objects is still returned as null. So how do I access the fragment and thus accessa method of that fragment from host acticty.
Secondly, I am trying to use the action_service (its shown as Start button just for this mockup) in action bar as a toggle for satrting or stopping a background service. I can easily update the title/icon for start menu item from onOptionsItemSelected method (I save the current status running/stoppede in shared-preferences). but when I try to accees the menuItem at onStart/onResume of the activity by using
MenuItem mi = (MenuItem) findViewById (R.id.action_service);
it always returns null. So How Can I access action_service menu Item in onResume/onStart to update it.
My Application looks like this
First of all if you want to declare MenuItem, you should do it in this way :
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main_activity, menu);
MenuItem mRefresh = menu.findItem(R.id.refresh_menu_item);
return true;
}
About updating your Fragment on applications load or Activity's start, just set selected the tab which holds your Fragment and put the code which will load the data in your Fragment on it's onStart() or onActivityCreated() method. You can override onOptionsItemSelected() in your Fragment, so you can update your views not from your Activity which holds your Fragment, but from it's own class.
Edit: Here is an example how you should handle menu from your Fragment :
public class MyFragment extends Fragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true); // Do not forget this!!!
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.first_fragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.action_refresh:
// Do You stuff here
break;
}
return super.onOptionsItemSelected(item);
}
}
Using this you can add and use MenuItem's in your Fragment.
Hope this helps!
I can answer the MenuItem part just not the other part.
for the menu item as per the docs You can safely hold on to menu (and any items created from it), making modifications to it as desired, until the next time onCreateOptionsMenu() is called.
for example
#Override
public boolean onCreateOptionsMenu(Menu menu) {
actionMenu = menu;
return true;
}
so basically anytime you want to change one of the items you can do this
MenuItem item = actionMenu.getItem(0);

Re-using Options menu code

Is there a convenient way of showing the same Options menu options in multiple Activities?
Example: In my app, I display a TV Guide in one of three ways.
Seven day guide (TabActivity with 7 tabs)
All channels 'Now showing' (ListActivity)
All shows today by start time (Activity - could be changed easily to ListActivity)
For the Options menu in the TabActivity, the code is quite simple...
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
menu.clear();
inflater.inflate(R.menu.gv_options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.view:
...
...
}
}
...but at the moment it seems I need to copy/paste it to the other two Activities which I don't like doing. If I change the Options menu code for one I'll need to do it for the other two also.
The only alternative I can think of is I have a 'helper' class (POJO) to which I could add a method and pass the context into to allow use of the getMenuInflator() method and another method I could pass the result of item.getItemId() into to process with the switch-case.
What is the normal way of having multiple Activities with the same Options menu?
Create a simple separate class with these two methods:
public class MyMenuHandler {
private Activity mActivity;
public MyMenuHandler(Activity activity) {
mActivity = activity;
}
public boolean onPrepareOptionsMenu(Menu menu) {
MenuInflater inflater = mActivity.getMenuInflater();
menu.clear();
inflater.inflate(R.menu.gv_options_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.view:
...
}
}
}
In your activities override those callback methods and redirect the call to an instance of your MyMenuHandler class:
public class MyActivity1 extends TabActivity {
private MyMenuHandler mMenuHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
...
mMenuHandler = new MyMenuHandler(this);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// you may also add here some items which are specific
// for one activity, not for the others
...
return mMenuHandler.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle selection of your specific items here,
// if none of them has been selected call mMenuHandler method
...
return mMenuHandler.onOptionsItemSelected(item);
}
}
This will let you hold in one place the code which respond to selection of your basic menu items, so there will be no need to worry about copy-pasting it to all activities which are to have the same menu.
One approach is to use inheritance with your Activities. Create a base Activity that implements the options menu methods and then each child Activity will gain that functionality. This is the recommended approach on the Android developer site:
Tip: If your application contains multiple activities and some of them provide the same Options Menu, consider creating an activity that implements nothing except the onCreateOptionsMenu() and onOptionsItemSelected() methods. Then extend this class for each activity that should share the same Options Menu. This way, you have to manage only one set of code for handling menu actions and each descendant class inherits the menu behaviors.
Unfortunately this won't work for you as you are not inheriting from Activity itself but differing subclasses of it, but that is the 'normal' way to do it.
You can encapsulate your action menu in a fragment. In this way you only need to add the fragment in the onCreate menu of your activity.
You need to call setHasOptionsMenu once the fragment is created.
To add the add fragment use a tag instead of a layout id.

Same option menu in all Activities in Android

I have 10-15 activities in my project. I want to have the option menu mostly in all Activities. Then is their any way we can do it at one place and it appears in all activities.
Also, I will like to hide the option menu in some. So, is it possible or I have to write option menu code in all activities.
Regards
Sunil
Create a Class (say BaseActivity) that extends Activity, and override onCreateOptionsMenu and onOptionsItemSelected functions.
public class BaseActivity extends Activity {
// Activity code here
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item:
// do what you want here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Now, in the other 15-16 activities, instead of extending an Activity, you should extend BaseActivity.
public class FooActivity extends BaseActivity {
// Activity code here
}
This way, all your activities derive the options menu. For activities where you want the options menu disabled, you can override it again in that particular activity.
public class BarActivity extends BaseActivity {
// Activity code here
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Do Nothing
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Do Nothing
}
}
Hopefully, it doesn't give you problems in the manifest file.
The solution to this problem is in your new activity add this menu method.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_home_page, menu);
menu.removeItem(R.id.logout);
return true;
}
In each activity this method will automatically appear.
If it doesn't then add it with the inflate call. It requires two parameters, an xml resource(the same one that you used in your original activity), and the menu object that is pass into the onCreateOptionsMenu method.
menu.removeItem will remove the menu item of whatever resource id you pass to it.
I hope this helps those who are facing this problem.
Thank you, and happy to share this post.
It is not enough to just extend the BaseActivity, you must also call super.onCreateOptionsMenu(menu) and super.onOptionsItemSelected(item) like this in your other activities:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//getMenuInflater().inflate(R.menu.menu_second, menu); <- remove this
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}

Categories

Resources