片段中的getSupportFragmentManager()未定义

时间:2015-07-24 14:00:08

标签: android android-fragments android-support-library

我在getSupportFragmentManager()上遇到错误“此方法在Fragment中取消定义”,同时使用滑动选项卡创建滑块菜单我准备了代码如下所示..

public class HomeFragment extends Fragment {

    Toolbar toolbar;
    ViewPager viewpager;
    ViewPagerAdapter adapter;
    SlidingTabLayout tabs;
    CharSequence Titles1[] = { "Home", "Help", "Contect" };
    // int Titles[] = { R.drawable.ic_content_copy_black_24dp,
    // R.drawable.ic_refresh_black_24dp, R.drawable.ic_share_black_24dp };
    int NumOfTabs = 3;

    public HomeFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_home, container,
            false);

        return rootView;

        adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles1,
            NumOfTabs);

        viewpager = (ViewPager) rootView.findViewById(R.id.pager);
        viewpager.setAdapter(adapter);

        tabs = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
        tabs.setDistributeEvenly(true);
    }

我的ViewPager适配器类如下所示

public class ViewPagerAdapter extends FragmentStatePagerAdapter{

    CharSequence Titles1[];
    int Titles[];
    int NumbOfTabs;

    public ViewPagerAdapter(FragmentManager fm, CharSequence mTitles[], int mNumbOfTabs) {
        super(fm);
        this.Titles1 = mTitles;
        this.NumbOfTabs = mNumbOfTabs;
    }

    @Override
    public Fragment getItem(int arg0) {

        if(arg0 == 0){
            Tab1 tab1 = new Tab1();
            return tab1;
        }else if(arg0 == 1){
            Tab2 tab2 = new Tab2();
            return tab2;
        }else{
            Tab3 tab3 = new Tab3();
            return tab3;
        }
    }


    @Override
    public CharSequence getPageTitle(int position) {
        return Titles1[position];
    }

    @Override
    public int getCount() {
        return NumbOfTabs;
    }

3 个答案:

答案 0 :(得分:4)

只需替换:

Application_EndRequest

使用:

getSupportFragmentManager()

如果您使用的是getFragmentManager() ,则会返回android.support.v4.app.Fragment(SupportFragmentManager)

如果您使用的是android.support.v4.app.FragmentManager,则会返回android.app.Fragment

请注意,它与android.app.FragmentManager中的Activities.Like中的处理方式不同。你有android.support.v4.app.FragmentActivitygetSupportFragmentManager()

答案 1 :(得分:1)

getSupportFragmentManager()延伸activityFragmentActivity时,会使用

AppCompatActivity。如果您要延长Activity,则需要使用getFragmentManager()

如果您要展开FragmentActivity,请确保导入android.support.v4.app.FragmentActivity

另请注意,getSupportFragmentManager()可用android.support.v4.app.Fragment而不是android.app.Fragment

您还需要在rootView结束时返回onCreateView()

答案 2 :(得分:0)

你确定你有正确的导入吗? 这一个:import android.support.v4.app.Fragment; 而不是这个:import android.app.Fragment;

编辑: 请注意,您的代码在"之后返回rootView"在onCreateView上永远不会被执行,因为你之前有过返回。