I am using fixed tabs + swipe inside a FragmentActivity. I have added a menu in action bar. I want that when the menu is clicked it should open class based on the current tab that is selected.
static TabHost myTabs;
-
-
-
myTabs = getTabHost();
This shows an error asking me if it shouls create a method called getTabHost(). I am assuming its because I am using FragmentActivity instead of Activity. So how do I know which tab is selected?
EDIT
As told below I have done this
#Override
public void onAttachFragment(Fragment fragment){
super.onAttachFragment(fragment);
tabValue=fragment.getId();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.one, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (tabValue) {
case 0:
Toast.makeText(BarcodeActivity.this, "HELLO", Toast.LENGTH_LONG).show();
case 1:
Intent i = new Intent(BarcodeActivity.this, NewCodeAdder.class);
startActivity(i);
break;
}
return true;
}
But still nothing happens when I click on the menu add option.
Check this out, it has everything from id to finding names of tabs:
Get the current fragment object
Related
How to create optionmenu for Android 3.0 and higher version mobiles?
I am trying to create options menu in my Android program. I am using the following code to inflate options menu. option menu icon not showing in higher version mobiles..
public class MainScreenTab extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Merchants", "Personal Payee" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen_tab_layout);
//Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu); //inflate our menu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
// switch(item.getItemId()) {
int id = item.getItemId();
if (id == R.id.item_refresh) {
Intent i = new Intent(MainScreenTab.this,ListMerchantType.class);
startActivity(i);
return true;
}
else if (id == R.id.item_save) {
Intent i = new Intent(MainScreenTab.this,ListPayee.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
}
You just need to use this Reflection method to force your icon in the ActionBar
public static void forceOverFlowIconInActionBar(Activity mActivity)
{
try
{
ViewConfiguration config = ViewConfiguration.get(mActivity);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null)
{
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Try this one. import java.lang.reflect.Field; And on your onCreateOptionsMenu() method just simply add:
if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
try {
Field field = menu.getClass().getDeclaredField("mOptionalIconsVisible");
field.setAccessible(true);
field.setBoolean(menu, true);
} catch (Exception ignored) {
ignored.printStackTrace();
}
}
and don't forget to add this to your xml menu android:icon="#drawable/blah_blah" . Hope it helps. And don't forget to up-vote if it is helpful.
Menus: Generally a list of commands or facilities displayed on screen. It is a common user interface for the user. If you want to provide a familiar and consistent user experience you should use Menus in your activity. It is beginning with android 3.0(Api level 11). So design and user experience my change for device to device that is depends on the Menu apis.
There mainly there menus in the android. Those are Options menu, Context menu, Popup Menu.
Options menu:
Options menu is a collection of menu items for an activity. The place where you locate icons that is very impact to the app. Such menu items are search, settings, compose email.
If you are developing the options menu for Android 2.3 and lower user can reveal the options menu by pressing menu button. On the 3.0 and higher the options menu items as a combination of action bar items. Beginning with Android 3.0, the Menu button is deprecated (some devices don't have one), so you should migrate toward using the action bar to provide access to actions and other options.
Creating Options Menu in android
Simply options menu is where you should you include options and other actions what are relevant to activity. The item in the options menu is depends on the version you are using.
If it is below 3.0 that comes when you press the menu buttons. If it is higher that will comes to the top of the screen. Means that will include with the action bar screen.
You can declare items for the options menu from either your Activity subclass or a Fragment subclass. At one time if you declare both the items in the activity then that will appear one followed another. You can also reorder the menu items in the android:orderInCategory attribute in each you need to move.
To specify a menu item in the activity first you need to override one method. That method is onCreateOptionsMenu() . This mehtod fragments provide their own onCreateOptionsMenu() callback.
Example:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}
We can perform add and retrieve options in the menu item api by using add() and findItem().
Handling click events in onCreateOptionsMenu():
If you want to provide a click event on the menu items the system calls onOptionsItemSelected. In that method you can identify which item you are selected by using item.getItemId(). which returns the unique ID for the menu item (defined by the android:id attribute in the menu resource or with an integer given to the add() method). You it is matched you can perform your action whatever you want.
Example:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
newGame();
return true;
case R.id.help:
showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
When you successfully handle the menu item that will returns true. If not handle that item that will you should call the superclass implementation of onOptionsItemSelected().
Changing menu items at runtime:
When you call onCreateOptionsMenu() that is displaying simple onCreateOptionsMenu(). you can not change the items in the run time. If you want to change the items in the run time you need to call onPrepareOptionsMenu() method. This method passes you the Menu object as it currently exists so you can modify it, such as add, remove, or disable items.
Example Project:
Open your eclipse and create one project name called OptionsMenu.
In that open you menu folder in the resource folder. In the main.xml file add how many items you want. You can get main.xml file below.
Main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#+id/menu_settings" android:orderInCategory="100"
android:showAsAction="never" android:title="#string/menu_settings"/>
<item android:id="#+id/item1" android:title="Tutorial 1"></item>
<item android:id="#+id/item2" android:title="Tutorial 2"></item>
<item android:id="#+id/item3" android:title="Tutorial 3"></item>
<item android:id="#+id/item4" android:title="Tutorial 4"></item>
<item android:id="#+id/item5" android:title="Tutorial 5"></item>
</menu>
Here i used #string/menu_settings so you can add that item in the strings.xml file.
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">OptionsMenu</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
</resources>
Once that is done open your main activity. In that write the onCreateOptionsMenu method for adding the menu item to the activity. Once that is done if you want to give click events you write onOptionsItemSelected. You can get the complete code below.
MainActivity
package com.tutorialindustry.optionsmenu;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
Toast.makeText(this, "Tutorial 1 Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.item2:
Toast.makeText(this, "Tutorial 2 Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.item3:
Toast.makeText(this, "Tutorial 3 Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.item4:
Toast.makeText(this, "Tutorial 4 Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.item5:
Toast.makeText(this, "Tutorial 5 Selected", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Once that is done run you project that you can get the below output. In this way we can perform options menu in the android.
I am developing an app using actionbar sherlock. The problem I have is that I have the menus setup and all my xml files are correct since I get no compiler and logcat error.
THe problem I am having is that when I load a fragment A with its own specific menu everything is good. But when I then move to another fragment B, fragment A menu appears on fragment B. Any ideas as to whats causing this.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.product_allergy, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case R.id.productClear:
addtoList();
break;
}
return true;
}
The menu is belonged to Activty rather than fragments. Fragment A and B are in same activity, so when A adds some items into activity's menu and then it is replaced by Fragment B, the activity does not change, i.e., the menu is still there.
If you want your Fragment B to have different menu items, override the onCreateOptionsMenu() method, remember to setHasOptionsMenu(true) in Fragment's onCreate() method.
FYI, if you simply want to clear prior fragment's menu item, call menu.clear() in onCreateOptionsMenu().
EDIT:
When you are trying to handle the action bar callback in fragments, you should do something like below:
#override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.fragmentActionBarButton:
//your code
return true;
default:
return super.onOptionsItemSelected(item);
}
}
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);
I am having trouble getting the following piece of code to work out. I have a viewpager with 3 fragments, and I want a search icon to only show up on one. I started off trying to add the search function by the fragment, but the rendering of the menu item was slow when swiping to that page. I am now on the part to add the search icon to the activity, and then just hide or show depending on which viewpager page is active, but the following is not working:
public class MyApp extends FragmentActivity implements
FragmentTeams.FragmentNotification,ViewPager.OnPageChangeListener,
OnNavigationListener{
...
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
menuSearch = menu.findItem(R.id.menu_search);
mSearchView = new SearchView(this);
menuSearch.setActionView(mSearchView);
menuSearch.setVisible(false);
return true;
}
#Override
public void onPageSelected(int pageNum) {
if(pageNum== 1){
ActionBar actionBar = MyApp.this.getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
menuSearch.setVisible(true);
invalidateOptionsMenu();
}else{
ActionBar actionBar = MyApp.this.getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
menuSearch.setVisible(false);
invalidateOptionsMenu();
}
}
While the above does (appear to) create and hide the icon at onCreateOptionsMenu, it is not reenabled when moving to
pageNum ==1
Can anyone give me some insight as to why this may be happening?
invalidateOptionsMenu make the system calls the method onPrepareOptionsMenu, so you can override this method as follows:
public boolean onPrepareOptionsMenu(Menu menu) {
int pageNum = getCurrentPage();
if (pageNum == 1) {
menu.findItem(R.id.menu_search).setVisible(true);
}
else {
menu.findItem(R.id.menu_search).setVisible(false);
}
}
public void onPageSelected(int pageNum) {
invalidateOptionsMenu();
}
You can implement onCreateOptionsMenu() in your Fragment and set 'setHasOptionsMenu(true)' for the fragment
a possible solution for this problem would be inflating your custom menu inside the activity hosts your ViewPager and getting a menu reference as below:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.custom_menu, menu);
customMenu = menu;
return super.onCreateOptionsMenu(menu);
}
after that you can easily hide/show the menu's items without any delay inside onPageSelected method as below:
#Override
public void onPageSelected(int position) {
switch (position) {
case 0: {
customMenu.getItem(0).setVisible(false);
break;
}
case 1: {
customMenu.getItem(0).setVisible(true);
break;
}
}
I used Nermeen's answer and managed to get it without any delay.
I don't inflate anything in onCreateOptionsMenu, but use it to get a reference to the menu:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
customMenu = menu;
return super.onCreateOptionsMenu(menu);
}
Then, in onPrepareOptionsMenu(), I call the viewpager getCurrentItem() (should be something like viewPager.getCurrentItem()), call invalidateOptionsMenu() and inflate whatever menu I want in that page using the customMenu reference I created in onCreateOptionsMenu().
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;
}
}