我想重写公共函数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
我做错了什么?
答案 0 :(得分:0)
Your fragment should be extending the android.support.v4.Fragment
.
And apart from that, you should use an Empty Constructor in your fragment.
You can also use newInstance method if you want to pass some data in your fragment:
In Fragment:
public static TestFragment newInstance(int type) {
TestFragment f = new TestFragment();
Bundle b = new Bundle();
b.putInt("type", type);
f.setArguments(b);
return f;
}
Your getItem
would look like this:
@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;
}
TestFragment1
and TestFragment2
is similar to your TestFragment
.