RobbieP14383
RobbieP14383

Reputation: 145

Using Fragments for ViewPager in Android

Can anyone tell me why this isnt working? I havent changed this file since it worked last but now I get the error below:

import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity {

private final static int NUM_PAGES = 2;
private ViewPager mPager;
private ScreenSlidePagerAdapter mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);

// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
mPager.setAdapter(mAdapter);
mPager.setCurrentItem(2);
}

private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int i) {

    Fragment frag = null;

    switch (i) {
    case 0:
        frag = new PageOneFragment();
        break;
    case 1:
        frag = new PageTwoFragment();
        break;

    }
    return frag;
}

@Override
public int getCount() {
    return NUM_PAGES;
}
}
}

The error is on "frag = new PageTwoFragment();" which states "Type mismatch: cannot convert from PageTwoFragment to Fragment".

Maybe I should create two projects from now on, last good version and then current working project. Is this something other people do?

Thanks

Upvotes: 1

Views: 2331

Answers (2)

Philipp Jahoda
Philipp Jahoda

Reputation: 51411

You imported the wrong Fragment.

You need to import android.support.v4.Fragment

Furthermore, your adapter only handles 2 Fragments. Therefore calling

ViewPager.setCurrentItem(2);

will cause problems, since the index for the first fragment is 0.

Upvotes: 1

flx
flx

Reputation: 14226

The Problem is, that you are mixing Android Fragments how there were introduced in API11 and Fragments from android support library.

You have to use one or the other, but not both.

Change your imports to

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;

And change getFragmentManager() to getSupportFragmentManager().

And it will work using the support lib.

Calling mPager.setCurrentItem(2); with a pager of 2 Fragments crashs, though. Only 0 and 1 are valid values in your case.

Upvotes: 3

Related Questions