片段无法使用FragmentPagerAdapter打开

时间:2016-07-08 11:03:06

标签: android android-fragments

此行显示错误,应用停止工作。

fragmentTransaction.replace(R.id.fragment_container, fragment1);

主要活动

TimeTable fragment1 = new TimeTable(getSupportFragmentManager());
        android.support.v4.app.FragmentTransaction fragmentTransaction =getSupportFragmentManager().beginTransaction();
        //fragmentTransaction.replace(R.id.fragment_container,);
        fragmentTransaction.replace(R.id.fragment_container, fragment1);
        fragmentTransaction.commit();

TimeTable 片段

public class TimeTable extends FragmentPagerAdapter {


public TimeTable(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int i) {

    switch (i) {
        case 0:
            tab1 t1 = new tab1();
            return t1;
        case 1:
            tab2 t2 = new tab2();
            return t2;
        case 2:
            tab3 t3 = new tab3();
            return t3;

    }
    return null;
}

@Override
public int getCount() {
    return 3;
}//set the number of tabs

@Override
public CharSequence getPageTitle(int position) {
    Locale l = Locale.getDefault();
    switch (position) {
        case 0:
            return "Monday";
        case 1:

            return "Tuesday";
        case 2:

            return "Wednesdey";
    }
    return null;
}
}

2 个答案:

答案 0 :(得分:0)

如果您使用FragmentPagerAdapter,那么为什么要替换片段?只需设置TimeTable。

TimeTable mAdapter = new TimeTable (getSupportFragmentManager());
ViewPager mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);

请检查链接: - http://www.truiton.com/2013/05/android-fragmentpageradapter-example/

答案 1 :(得分:0)

好像您正在使用ViewPager。 但这不是使用它的方式。

内部有Viewpager的布局。

private ViewPager pager;
private TimeTable timeTable;

- >像这样设置适配器

pager = (ViewPager)findViewById(R.id.vpSettingPages);
t1 = new TimeTable(getSupportFragmentManager())
pager.setAdapter(timeTable);

您也可以看到此https://developer.android.com/training/animation/screen-slide.html以供参考。