将SectionsPagerAdapter与自定义片段一起使用

时间:2013-05-16 20:07:16

标签: android android-fragments android-tabs

使用holo片段和标签以及sectionsPagerAdapter创建模板项目时,您会得到类似这样的内容

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        Fragment fragment = new DummySectionFragment();
        Bundle args = new Bundle();
        args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
        fragment.setArguments(args);
        return fragment;
    }

DummySectionFragment的定义:

/**
 * A dummy fragment representing a section of the app, but that simply displays dummy text.
 */
public static class DummySectionFragment extends Fragment {
    public DummySectionFragment() {
    }

    public static final String ARG_SECTION_NUMBER = "section_number";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        TextView textView = new TextView(getActivity());
        textView.setGravity(Gravity.CENTER);
        Bundle args = getArguments();
        textView.setText(Integer.toString(args.getInt(ARG_SECTION_NUMBER)));
        return textView;
    }
}

现在我用我自己的Fragment扩展名替换这段代码:

@Override
    public Fragment getItem(int i) {
        Fragment fragment = new TargetsFragment();
        Bundle args = new Bundle();

我在自己的文件中定义了这个:

public class TargetsFragment extends Fragment {
boolean mDualPane;
int mCurCheckPosition = 0;


private CheckedExpandableListAdapter expandableListAdapter;
private ExpandableListView expandableListView;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

  //TODO: serve with correct data instead of this!
        final ArrayList<ListNode> dummyList = buildDummyData();
        loadHosts(dummyList);
    }
    [...]

我得到的错误是无法在getItem中将TargetsFragment转换为Fragment。我觉得我在这里缺少一些简单的东西。但是什么?如果您需要更多代码,请询问。

1 个答案:

答案 0 :(得分:3)

解决方案:仔细查看导入。确保在两个类中导入和扩展相同的片段。例如android.app.fragment或import android.support.v4.app.Fragment;