Incompatilble types in my FragmentPagerAdapter

2019-03-03 13:45发布

问题:

I get an error when I try to return a new fragment. I suspect it has something to do with the imports but I must be wrong using just Android's fragmentpageradapter does not change anything, I'm out of ideas and just want it to work so I can see it in the emulator running.

My FragmentPagerAdapter class:

import android.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;


/**
 * Created by HP_user on 01/12/2015.
 */
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
    final int PAGE_COUNT = 3;
private String tabTitles[] = new String[] { "Home", "Shouts", "Shouters" };


public SampleFragmentPagerAdapter(android.support.v4.app.FragmentManager fm) {
    super(fm);
}

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



@Override
public android.Fragment getItem(int position) {
    return Home.newInstance(position + 1);
}

@Override
public CharSequence getPageTitle(int position) {
    // Generate title based on item position
    return tabTitles[position];
   }
}

My main activity class:

public class MainActivity extends AppCompatActivity {


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

        // Get the ViewPager and set it's PagerAdapter so that it can display items
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager()));

        // Give the PagerSlidingTabStrip the ViewPager
        PagerSlidingTabStrip tabsStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        // Attach the view pager to the tab strip
        tabsStrip.setViewPager(viewPager);
    }

}

Main activity fragment class:

public class MainActivityFragment extends Fragment {

    public MainActivityFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_page, container, false);
    }
}

回答1:

The problem is that the android.support.v4.app.FragmentPagerAdapter class can only be used with support Fragments, i.e. android.support.v4.app.Fragment.

You have two choices to fix it.

Choice 1) Make all of your Fragments android.support.v4.app.Fragment instances instead of android.app.Fragment instances.

Choice 2) Use the android.support.v13.app.FragmentPagerAdapter class from the v13 support library, which makes it possible to use regular Fragments, see documentation here.