我正试着用这种方法
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();
}
}发布于 2013-10-27 21:02:16
关于你的第一个问题,这应该是可行的。MappingPage是Fragment类的间接实例,因此可以返回它。
关于第二个问题,您调用的方法总是返回一个特定类型,比如Fragment ( getItem() )。但是,这也可以是该子类的一个子类,如果您确定它是这样的,则可以将它安全地转换为该子类。
https://stackoverflow.com/questions/19623453
复制相似问题