0

作为标题,我在我的 APP 上使用了 ActionBarSherlock 和 SlidingMenu。

要在操作栏上添加菜单项,我所做的是:

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

在大多数情况下它运行良好,但有时我在启动我的应用程序时会收到此错误

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

我的APP刚刚崩溃...

为了遵循该错误消息,我确实在 MenuFragment 上添加了一个空构造函数,但我的 APP 有时仍会因相同的错误而强制关闭。

我还在 StackOverflow 中阅读了一些关于此的主题,但还不够了解。

我能做些什么来克服这个问题?

4

1 回答 1

0

好的,我终于用这个解决了这个问题

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

而不是这个

public class MenuFragment extends SherlockFragment
{
  public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
  {
    //Some stuff...
  }
}

并解决了我的问题。

于 2013-04-22T09:53:05.267 回答