2

我正在研究活动中的 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。这里应该是隐式向上转换,我不明白为什么它不起作用:(

//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;
    }
4

1 回答 1

0
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 -->

于 2016-09-03T07:11:58.150 回答