hi frnds am creating an application which is a tab application.
in my Home which extends sherlockFragmentActivity, i am inflating menu.xml and includes code for on optionMenuitem click listener. The Fragmentactivity contains tabhost and on each tab it load fragments. this is my menu.xml
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="always"
android:icon="@drawable/setting_selector"
android:title=""
>
<menu >
<item
android:id="@+id/Profile"
android:showAsAction="ifRoom"
android:title="Profile"/>
<item
android:id="@+id/chngDoctor"
android:showAsAction="ifRoom"
android:title="Change doctor"
android:visible="false"/>
<item
android:id="@+id/changePword"
android:showAsAction="ifRoom"
android:title="Change password"/>
<item
android:id="@+id/logout"
android:showAsAction="ifRoom"
android:title="Logout"/>
</menu>
</item>
and this is my onCreateOptionMenu and onOptionItemSelected methods in class Home
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getSupportMenuInflater().inflate(R.menu.main, menu);
SubMenu subMenu = (SubMenu) menu.getItem(0).getSubMenu();
if(userType.equals("admin"))
subMenu.getItem(1).setVisible(true);
else
subMenu.getItem(1).setVisible(false);
return true;
}
and this is my onOptionItemSelected method
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case R.id.Profile:
break;
case R.id.changePword :
break;
case R.id.chngDoctor :
break;
case R.id.logout:
Home.this.finish();
break;
}
return true;
}
i need to add some menus depending on tab change. that is on tab change i load different fragments and when fragment changes i need to add new items to the menu. my ListFrag which extends SherlockFragment and it will load when i click on the 3 rd tab. when this fragment load i need to add 1 menu item to the menu
Try the following way.
This may help you.
use
onPrepareOptionsMenu
method and clear all menu first usingthen add menu.
Also refer here.. check its
onPrepareOptionsMenu
methodhere is an example...it might help you...
In the
menu.xml
you should add all the menu items. Then you can hide items that you don't want to see in the initial loading.Add
setHasOptionsMenu(true)
in the onCreate() method to invoke the menu items in your Fragment class.You don't need to override
onCreateOptionsMenu
in your Fragment class again. Menu items can be changed (Add/remoev) by overridingonPrepareOptionsMenu
method available in Fragment.based on Gunaseelan answer