我正在尝试使用方法
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new MappingPage();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
我编写了一个名为MappingPage()的类,如果我尝试使用上面的方法,我创建的片段是MappingPage类型,因为它已被扩展,因此在函数返回片段时抛出错误(不是MappingPage对象) )
编辑:我在做
时收到错误 Fragment fragment = new MappingPage();
Eclipse告诉我,我需要将片段更改为MappingPage类型,这意味着我必须更改函数的返回类型
两个问题 1)你应该如何将自定义片段放入其中?
2)为什么dummySectionFrament返回片段对象而不是DummySectionFragment对象?
提前致谢
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
这是我的班级
public class MappingPage extends Fragment
{
private MapView map;
private MapController myMapController;
public static final String ARG_SECTION_NUMBER = "1";
public MappingPage() {
}
public View onCreateView (LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Context context = new ContextThemeWrapper(getActivity(), R.style.fragment_theme);
//LayoutInflater Inflater = inflater.cloneInContext(context);
View view=inflater.inflate(R.layout.fragment_main_dummy, container, false);
return view;
}
@Override
public void onResume() {
map = (MapView)getActivity().findViewById(R.id.openmapview);
map.setBuiltInZoomControls(true);
myMapController = map.getController();
myMapController.setZoom(15);
super.onResume();
}
}
答案 0 :(得分:0)
关于你的第一个问题,这应该有效。 MappingPage
是Fragment
类的间接实例,因此您可以将其返回。
关于问题二,您调用的方法始终返回特定类型,例如Fragment
的{{1}}。但是,这也可以是它的子类,如果你确定它,你可以安全地将它强制转换为该子类。