Nino van Hooff
Nino van Hooff

Reputation: 3893

use SectionsPagerAdapter with custom fragment

When creating a template project with holo fragments and tabs and sectionsPagerAdapter you get something like this

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

The definition of 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;
    }
}

Now I replace this code with my own extension of Fragment:

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

I defined this in its own file:

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);
    }
    [...]

The error I get is that it is not possible to convert TargetsFragment to Fragment in getItem. I feel i'm missing something simple here. But what? If you need more code please ask.

Upvotes: 0

Views: 3597

Answers (1)

Nino van Hooff
Nino van Hooff

Reputation: 3893

Solution: take a close look at the imports. Make sure you import and extend the same Fragment in both classes. eg android.app.fragment or import android.support.v4.app.Fragment;

Upvotes: 3

Related Questions