Android Studio - 无法解析方法getSupportFragment()

时间:2014-07-02 11:47:16

标签: android android-fragments android-studio

以下是我在DrawerItemClickListener.java中的代码。 getFragmentManager()和getActionBar()为红色,表示无法解析方法。我该如何解决这个问题?

公共类DrawerItemClickListener实现ListView.OnItemClickListener {

private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    selectItem(position);
}

private void selectItem(int position) {

    Fragment fragment = null;

    switch (position) {
        case 0:
            fragment = new CreateFragment();
            break;
        case 1:
            fragment = new ReadFragment();
            break;
        case 2:
            fragment = new HelpFragment();
            break;

        default:
            break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        getActionBar().setTitle(mNavigationDrawerItemTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);

    } else {
        Log.e("MainActivity", "Error in creating fragment");
    }
}

}

2 个答案:

答案 0 :(得分:0)

使用

FragmentManager fragmentManager = ((YourFragmentActivity)activity).getFragmentManager(); 

而不是

FragmentManager fragmentManager = getFragmentManager();

答案 1 :(得分:0)

如果您在getSupportFragmentManager(),我认为您应该尝试Activity。 也许它会有所帮助