【问题标题】:Return Class which includes Fragments包含片段的返回类
【发布时间】:2017-05-16 09:10:37
【问题描述】:

我想重写公共函数 getItem(int position):

public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    Tab1Content tab1 = new Tab1Content();
                    return tab1;
                case 1:
                    Tab2Content tab2 = new Tab2Content();
                    return tab2;
                case 2:
                    Tab3Content tab3 = new Tab3Content();
                    return tab3;
            }
            return null;
        }
}

Tab1Content 如下所示:

public class Tab1Content extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.tab1_content, container, false);
        return rootView;
    }
}

但 Android Studio 在日志中抛出错误:

Error:(141, 28) error: incompatible types: Tab1Content cannot be converted to Fragment

我做错了什么?

【问题讨论】:

  • 在适配器的导入行下方添加:import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; 并在片段类中添加以下导入:import android.support.v4.app.Fragment;

标签: java android fragment


【解决方案1】:

您的片段应该扩展android.support.v4.Fragment

除此之外,您应该在片段中使用空构造函数。

如果你想在你的片段中传递一些数据,你也可以使用 newInstance 方法:

在片段中:

   public static TestFragment newInstance(int type) {

        TestFragment f = new TestFragment();
        Bundle b = new Bundle();
        b.putInt("type", type);

        f.setArguments(b);

        return f;
    }

您的getItem 将如下所示:

@Override public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return TestFragment.newInstance(1);
            case 1:
                return TestFragment1.newInstance(2);
            case 2:
                return TestFragment2.newInstance(3);
        }
        return null;
    }

TestFragment1TestFragment2 与您的 TestFragment 相似。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多