Adding Menu Item dynamically from SherlockActionBar Fragment Tabs - android

So I've been working on and Android app that has a Navigation Bar on the top with several Tabs, and that part is working fine but now I want to be able to dynamically add Menu Items to the Action Bar from different Fragments (since some Fragments may have different options available). So far no matter what I've tried I can't seem to get the onCreateOptionsMenu to be called. Here's what I have so far
//First I have a holder class that is used to navigate between the different Fragment Tabs
public class ActionHolder extends SherlockFragmentActivity implements ActionBar.TabListener {....
//And then I have this method for switching Fragments based on what Tab is selected
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
int selectedTab = tab.getPosition();
if (selectedTab == 0) {
SalesMainScreen salesScreen = new SalesMainScreen();
ft.replace(R.id.content, salesScreen);
}
else if (selectedTab == 1) {
ClientMainScreen clientScreen = new ClientMainScreen();
ft.replace(R.id.content, clientScreen);
}.....
Now here is one of the Tab's Fragments (the SalesMainScreen) that I want to have a few menu items added to the Action Bar
#Override
public void onCreate (Bundle savedInstanceState) {
Log.i("message","the oncreate method was called");
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved) {
return inflater.inflate(R.layout.salesmainscreen, group, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
Log.i("message", "the oncreatemenu method called");
inflater.inflate(R.menu.menu_refresh, menu);
super.onCreateOptionsMenu(menu, inflater);
}
I see the OnCreate Log message being called but I don't see the onCreateOptionsMenu Log being called at all. Also, I know that sometimes the imports cause issues, but when I import the Sherlock Menu and Menu Inflater I get all kinds of error messages on the OnCreateOptionMenu method about them not being compatible. Is it possible in this setup to dynamically add Menu Items to the Action Bar, or should I just add the items and then just don't do any actions on the ones that don't apply to the fragment that is being displayed?

I have an app using SherlockActionBar and tabs, with each tab containing a SherlockFragment. The main activity has its own menu in the action bar, and one of the fragments adds a search item to the action bar menu.
The main activity has the following:
class MainActivity extends SherlockFragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
ActionBar bar = getSupportActionBar();
bar.addTab(createThingOneTab());
bar.addTab(createThingTwoTab());
bar.addTab(createThingThreeTab());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.activity_main, menu);
}
}
The fragment in the tab has the following:
class ThingOneFragment extends SherlockFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
MenuItem search = menu.add("Search");
search.setIcon(android.R.drawable.ic_menu_search);
search.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
...
}
}
When I start the main activity, the tab shows ThingOneFragment by default and I see the search icon in the action bar. When I select the other tabs, the search icon disappears. You do need to make sure that you are using the Sherlock classes for Menu, MenuInflater, etc.
I'm not sure if it makes a difference but my TabListener looks like this:
private TabListener createTabListener(final Class<? extends Fragment> clazz) {
return new TabListener() {
private Fragment mFragment;
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// no action
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (mFragment == null) {
mFragment = Fragment.instantiate(activity, clazz.getName());
}
getSupportFragmentManager().beginTransaction()
.replace(android.R.id.content, mFragment)
.commit();
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// no action
}
};
I'm not sure if that is causing your issue or if it's even the correct way of handling tabs but I include it for completeness.

Related

Action bar menu item not working in fragment

I am working on a navigation drawer in which i am using multiple fragment .In one of the fragment i have to use menu item for some action .Now i can inflate menu item on action bar on that fragment but action is not performing .
public class Location extends Fragment implements View.OnClickListener {
GoogleMap googleMap;
Fragment fragment;
Button arrived_mbtn;
TextView current_mtv,request_mtv;
LinearLayout btn_mlayout,journey_mlayout;
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_location, container, false);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("you are in oncreate", "dfsdfsd");
setHasOptionsMenu(true);
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
try {
if (fragment != null) {
fragment = getFragmentManager().findFragmentById(R.id.map);
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
} catch (Exception e) {
e.printStackTrace();
}
Thread.interrupted();
super.onPause();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.menu_payment_card_detail,menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.action_settings:
Toast.makeText(getActivity(),"hello",Toast.LENGTH_SHORT);
return true;
}
return super.onOptionsItemSelected(item);
}
}
by this code an item is inflate on action bar but on click it did,t show any thing .
Change like this. You have not called show() on toast.
case R.id.action_settings:
Toast.makeText(getActivity(),"hello",Toast.LENGTH_SHORT).show();
Change your onCreateOptionsMenu method as below.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_payment_card_detail,menu);
}
And whatever id you have applied to your menu item, use that in the condition to check whether that menu item is clicked or not.
in your code:
Move the setHasOptionsMenu(true) in the onCreateView() method;
Use inflater.inflate(R.menu.menu_payment_card_detail,menu); in the
onCreateOptionsMenu method.
Something like this:
#Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_payment_card_detail,menu);
super.onCreateOptionsMenu(menu, inflater);
}
Add the show() method to your Toast Toast.makeText(getActivity(),"hello",Toast.LENGTH_SHORT).show();
In fragment:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set setHasOptionsMenu
setHasOptionsMenu(true);
}
Check the parent activity doesn't eat the item selected, i.e. make sure if the parent activity implements onOptionsItemSelected() that it returns false for your fragment's items.

Android - How to hide menu option for current fragment

I have an ActionBar activity with a FrameLayout and a menu. when the user clicks the menu item I replace the fragment with the relevant new fragment. However, I cannot see an obvious way to remove the menu item for the selected fragment.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
StudyFragment startFragment = new StudyFragment();
startFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add
(R.id.container, startFragment).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_study:
replaceFragment((Fragment)new StudyFragment());
break;
case R.id.action_list:
replaceFragment((Fragment)new ListFragment());
break;
// etc
}
return super.onOptionsItemSelected(item);
}
private void replaceFragment(Fragment f) {
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, f);
transaction.addToBackStack(null);
transaction.commit();
}
The Google documentation on changing menus says to disable the menu in onPrepareOptionsMenu - but how will I know which item has been selected?
--Solution Implemented--
Using Muhammed Refaat's solution below I added two new members to the class:
private Menu activityMenu;
private MenuItem curMenuItem;
Set them in onCreateOptionsMenu
activityMenu = menu;
curMenuItem = activityMenu.findItem(R.id.action_study);
curMenuItem.setVisible(false);
And changed them on onOptionsItemSelected
curMenuItem.setVisible(true);
curMenuItem = activityMenu.findItem(id);
curMenuItem.setVisible(false);
First get the item you want to remove :
MenuItem item = menu.findItem(R.id.your_action);
then set it's Visibility false :
item.setVisible(false);
and if the problem is in getting the menu (as it's not in the fragment), you can easily get a context from the activity that contains the menu and get the menu by it.
Inside your fragment you will have to use setHasOptionsMenu(true); in order to access options menu from within your fragment.
Code (inside your second fragment where you wanna hide the item):
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO your code to hide item here
super.onCreateOptionsMenu(menu, inflater);
}
Similarly, for your fragment where you want to show that MenuItem you can do the similar thing.
In the fragment where you want to hide the Item
#Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item=menu.findItem(R.id.action_search);
item.setVisible(false);
and in onCreate() of your fragment
setHasOptionsMenu(true);
Adding to Muhammed's answer above. Once the item has been set as invisible, you may need to also disable the item. Note Google's comment: "Even if a menu item is not visible, it may still be invoked via its shortcut (to completely disable an item, set it to invisible and disabled)" under setVisible() in the MenuItem documentation.
Thus:
item.setVisible(false);
item.setEnabled (false);
Add below codes into your fragment
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem item = menu.findItem(R.id.save);
item.setVisible(false);
}
// create Boolean variable in the main activity
private var menuvisibile: Boolean = true
// while navigating fragments set the menuvisibile value and use it
// variable as part of the return statement
invalidateOptionsMenu()
menuvisibile = false
override fun onCreateOptionsMenu(menu: Menu?): Boolean
{
val menuInflater = menuInflater
menuInflater.inflate(R.menu.notification,menu)
return menuvisibile
}
working well for me.

findFragmentByTag() is returning null when working with getSupportFragmentManager()

I am working with the support library ActionBar because I'm using an older minimum SDK. In the activity, I am using FragmentTabHost because I have 3 tabs. The ActionBar also has a SearchView, so when a search is made, the 3rd tab is switched out with the results of the search.
I am able to get intput from the SearchView, but I am unable to switch out the 3rd tab when I have a search result. I am using this as an example:
Dynamically changing the fragments inside a fragment tab host?
My problem is that when I try to get a reference to the 3rd tab, and I use getSupportFragmentManager().findFragmentByTag() , the fragment being returned is always null.
My base container that helps in swapping multiple fragments in a tab:
public class BaseContainerFragment extends Fragment{
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getChildFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
//Log.e("test", "pop fragment: " + getChildFragmentManager().getBackStackEntryCount());
boolean isPop = false;
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getChildFragmentManager().popBackStack();
}
return isPop;
}
}
A container that extends BaseContainerFragment
public class LibraryContainerFragment extends BaseContainerFragment {
private boolean mIsViewInited;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.e("test", "tab 1 oncreateview");
return inflater.inflate(R.layout.container_fragment, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e("test", "tab 1 container on activity created");
if (!mIsViewInited) {
mIsViewInited = true;
initView();
// setRetainInstance(true);
}
}
private void initView() {
Log.e("test", "tab 1 init view");
replaceFragment(new LibraryFragment, false);
}
}
The xml used to switch out fragments (container_fragment.xml):
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container_framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
My main activity:
public class BookSetup extends ActionBarActivity {
// For accessing SlidingMenu library
private SlidingMenu slidingMainMenu;
private FragmentTabHost mTabHost;
private SlidingMenu slidingContextMenuFavourites;
private SlidingMenu slidingContextMenuMyPrayerBook;
private SlidingMenu slidingContextMenuLibrary;
private android.support.v4.app.FragmentManager fragmentManager;
LibraryContainerFragment libraryContainerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Settings for the clickable top-left button in the action bar
android.support.v7.app.ActionBar bar = getSupportActionBar();
bar.setDisplayHomeAsUpEnabled(false);
bar.setHomeButtonEnabled(true);
bar.setIcon(R.drawable.main_menu);
// Setting up tabbed navigation
bar.setDisplayShowTitleEnabled(false);
// Setting up tabs
fragmentManager = getSupportFragmentManager();
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, fragmentManager, R.id.realtabcontent);
// Add tabs
mTabHost.addTab(mTabHost.newTabSpec("Favourites").setIndicator(getString(R.string.favourites) ),
FavouritesFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("My Book").setIndicator(getString(R.string.my_book) ),
MyBookFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Library").setIndicator(getString(R.string.library) ),
LibraryContainerFragment.class, null);
mTabHost.setCurrentTab(2);
//mTabHost.
// Creates a sliding animation when activity is started
overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu_with_search_context_menu, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
//SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
final MenuItem searchMenuItem = menu.findItem(R.id.action_search);
searchView = (android.support.v7.widget.SearchView) MenuItemCompat.getActionView(searchMenuItem);
//searchView = (SearchView)menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
//searchView.requestFocus();
searchView.requestFocusFromTouch();
//searchView.setIconifiedByDefault(true);
// Listener for the search input found in the action bar, when the magnifying glass is
// clicked
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
// Activated when a search string is submitted
#Override
public boolean onQueryTextSubmit(String query) {
// TODO : query is the text from the search view after you clicked search
if(query != null){
// If results are found, then switch the fragments
if(!sectionsFound.isEmpty()){
// Initialize the search fragment and send bundles of data to it
SearchLibraryResultFragment fragment = new SearchLibraryResultFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("values",
(ArrayList<? extends Parcelable>) sectionsFound);
bundle.putStringArrayList("names", sectionNames);
fragment.setArguments(bundle);
mTabHost.setCurrentTab(2);
libraryContainerFragment = (LibraryContainerFragment)fragmentManager.findFragmentByTag("Library");
((BaseContainerFragment) libraryContainerFragment.getParentFragment() ).replaceFragment(fragment,true );
return true;
}
});
}
}
This is the line that always returns null in BookSetup.java:
((BaseContainerFragment) libraryContainerFragment.getParentFragment() ).replaceFragment(fragment,true );
You are using the ChildFragmentManager to replace your Fragments right?
That might be your problem, instead of
libraryContainerFragment = (LibraryContainerFragment)fragmentManager.findFragmentByTag("Library");
use
libraryContainerFragment = (LibraryContainerFragment) getChildFragmentManager().findFragmentByTag("Library");

Actionbar items are duplicating

I have Action Bar in my application. I am adding action items using menu.xml. I am using action bar-compat as my support library. I observed a weird issue where my action items are getting duplicated.
I am finding this issue randomly when leave my device idle or work with other applications. Please find the screen shot and my code below:
private LoginWebActivity mContext;
private final String TAG = "LoginFragment";
// for metrics
private String mPageNameSignIn = "signin";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.webview, container, false);
return mView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mContext = (LoginWebActivity) getActivity();
initFragment();
}
#Override
public void onResume() {
super.onResume();
}
/**
* Initialises the views and variables of the fragment.
*/
#SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
protected void initFragment() {
mWebView = (WebView) mView.findViewById(R.id.webView);
Bundle b = mContext.getIntent().getExtras();
if (b != null) {
mUrl = b.getString(Constants.EXTRA_WEB_LOGIN_URL);
}
super.initFragment();
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.signin, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Navigate
switch (item.getItemId()) {
case R.id.menu_item_signup:
mContext.onSignUpClick();
break;
case android.R.id.home:
if (!goBack())
getActivity().finish();
default:
break;
}
return super.onOptionsItemSelected(item);
}
My XML :
<?xml version="1.0" encoding="utf-8"?>
<item
android:id="#+id/menu_item_signup"
allergy:showAsAction="ifRoom"
android:title="#string/sign_up">
</item>
You must clear your menu object before adding items. I had the same problem and this was the best solution that I've found.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.signin, menu);
super.onCreateOptionsMenu(menu, inflater);
}
Pretty late to this party, but for anyone that comes across this via the Google like I did, here's the real problem.
You didn't post your Activity code that's creating the Fragment, but I will venture to guess that it looks something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
Fragment fragment = ...
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
}
The problem with this is that when the activity goes through its lifecycle (which would happen "when leave my device idle or work with other applications", as you say), the system will save and restore the state of fragments for you. But with this code, you also are adding a new fragment to your Activity, so you end up with multiple fragments running in your activity, each adding an item to the menu.
While the posted workaround will address the duplicate menu entries issue, it would leave these extra fragment instances lying around, which is obviously not what you want.
The correct fix is a simple null check:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
if (savedInstanceState == null) {
Fragment fragment = ...
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
}
}
Since the system will indicate the activity is being recreated with a non-null Bundle for the savedInstanceState parameter, you check this to determine whether you should be creating and adding a new fragment.
Hope that helps.
i used Renan Bandeira's great solution and i had some error so i changed it a little bit and worked for me too . then I'm sharing my experience : maybe it become helpful again all credit goes to him for great solution .
#Override
public void onCreateOptionsMenu(Menu menu ) {
menu.clear();
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu."your current activity name ", menu);
return true;
}
I facing the same problem and exactly as state by #Szymon "I add menu option from the fragment, I create multiple fragments?" So my solution was look like below.
onCreate :
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.menu, menu);
menu.findItem(R.id.action_one).setVisible(true);
menu.findItem(R.id.action_two).setVisible(false);
super.onCreateOptionsMenu(menu, inflater);
}
onPrepare :
#Override
public void onPrepareOptionsMenu(Menu menu) {
if (isAdded()
&& !isDetached()
&& isVisible()
&& !isRemoving()
)
{
// show the menu
if (menu.findItem(R.id.action_one).isVisible())
menu.findItem(R.id.action_one).setVisible(true);
// hide the menu
if (menu.findItem(R.id.action_two).isVisible())
menu.findItem(R.id.action_two).setVisible(false);
}
}
You should use the following method instead and you will not see the duplicates anymore (notice that it has only a Menu object as argument)
#Override
public boolean onCreateOptionsMenu( Menu menu )
{
getMenuInflater().inflate( R.menu.main_activity_menu, menu );
return true;
}

Android ActionBarSherlock and SlidingMenu, Menu Fragment error

As title, I used ActionBarSherlock and SlidingMenu on my APP.
To add menu item on actionbar, what I did is:
public class Main extends SherlockFragmentActivity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setTheme(R.style.Theme_Sherlock);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
getSupportActionBar();
setContentView(R.layout.main);
FragmentManager fm=getSupportFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
menuFrag=fm.findFragmentByTag("f1");
if(menuFrag==null)
{
menuFrag=new MenuFragment();
ft.add(menuFrag, "f1");
}
ft.commit();
//...other stuff
}
/**
* A fragment that displays a menu. This fragment happens to not
* have a UI (it does not implement onCreateView), but it could also
* have one if it wanted.
*/
#SuppressLint("ValidFragment")
public class MenuFragment extends SherlockFragment
{
public MenuFragment(){}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
itemProgram=menu.add(0, MENU_ID_PROGRAMS, 0, getString(R.string.menuProgram));
itemProgram.setIcon(R.drawable.icon_programs_select).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
itemMyList=menu.add(0, MENU_ID_MYLIST, 0, getString(R.string.menuMyList));
itemMyList.setIcon(R.drawable.icon_mylist).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
itemPlaying=menu.add(0, MENU_ID_PLAYING, 0, getString(R.string.menuPlaying));
itemPlaying.setIcon(R.drawable.icon_playing).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}
}
}
In most time it runs well, but sometime I'll get this error when I start my APP
android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment
make sure class name exists, is public, and has an empty constructor that is public
And my APP just crashed...
To follow that error message, I did add an empty constructor on MenuFragment, but my APP sometime still force closed by same error.
I also read some thread about this in StackOverflow, but just not understand enough.
What can I do to overcome this problem ?
OK, I finally fixed this by using this
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
itemProgram=menu.add(0, MENU_ID_PROGRAMS, 0, getString(R.string.menuProgram));
itemProgram.setIcon(R.drawable.icon_programs_select).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
itemMyList=menu.add(0, MENU_ID_MYLIST, 0, getString(R.string.menuMyList));
itemMyList.setIcon(R.drawable.icon_mylist).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
itemPlaying=menu.add(0, MENU_ID_PLAYING, 0, getString(R.string.menuPlaying));
itemPlaying.setIcon(R.drawable.icon_playing).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return super.onCreateOptionsMenu(menu);
}
instead of this
public class MenuFragment extends SherlockFragment
{
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
//Some stuff...
}
}
And fixed my problem.

Categories

Resources