我正在活动中的Listfragment。
我在一个活动中有一个嵌套的类。

public static class DummySectionFragment extends ListFragment {
    /**
     * 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 contentView=inflater.inflate(R.layout.activity_main_fragment_browse, container);
        return contentView;
    }


但是编译器抱怨DummySectionFragemt不是片段

    @Override
public void onTabSelected(ActionBar.Tab tab,
        FragmentTransaction fragmentTransaction) {
    // When the given tab is selected, show the tab contents in the
    // container view.
    Fragment fragment = new DummySectionFragment(); // <-- complain not fragment
    // codes omitted .......
}


编译器投诉:
类型不匹配:无法从MainActivity.DummySectionFragment转换为Fragment

当我使DummySectionFragment直接扩展Fragment时,它可以工作,但是我只是不明白为什么它以前无法工作。显然,DummySectionFragment扩展了ListFragment并扩展了Fragment。这里应该是一个隐式的upcast,我不明白为什么它不起作用:(

//make it directly extends Fragment -->
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 contentView=inflater.inflate(R.layout.activity_main_fragment_browse, container);
        return contentView;
    }

最佳答案

public static class DummySectionFragment extends ListFragment {
    /**
     * 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;
        if(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)).equals("1")){
            rootView = inflater.inflate(R.layout.fragment_tab1,container, false);
        }
        else if(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)).equals("2")){
            rootView = inflater.inflate(R.layout.fragment_tab2,container, false);
        }
        else if(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)).equals("3")){
            rootView = inflater.inflate(R.layout.fragment_tab3,container, false);
        }
        else{
            rootView = inflater.inflate(R.layout.fragment_tab,container, false);
        }
        return rootView;
    }
}


//确保您使用import android.support.v4.app.ListFragment->

07-26 07:44