0

我正在尝试使用该方法

    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 告诉我需要将 fragment 更改为 MappingPage 类型,这意味着我必须更改函数的返回类型

两个问题 1)你应该如何把你的自定义片段放进去?

2) 为什么 dummySectionFrament 返回的是 Fragment 对象而不是 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();
}




}
4

1 回答 1

0

关于你的第一个问题,这应该有效。MappingPageFragment类的间接实例,因此您可以返回它。

关于问题二,你调用的方法总是返回一个特定的类型,比如Fragment. getItem()但是,这也可以是它的子类,如果您确定它是,您可以安全地将其转换为该子类。

于 2013-10-27T21:02:16.937 回答