ViewPager与Fragment结合使用

package com.example.pagerview_fragment;
/**
 * ViewPager与Fragment结合使用
 * 】FragmentPagerAdapter是v4包下的,
 *  Activity下的getFragmentManager()不是v4包下的,要用FragmentActivity

 */
import java.util.ArrayList;
import java.util.List;

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

public class MainActivity extends FragmentActivity {
    private ViewPager vp;
    private List l;
    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        vp=(ViewPager)findViewById(R.id.vp);
        l=new ArrayList();
        l.add(new MyFragment1());
        l.add(new MyFragment2());
        l.add(new Fragment3());
        adapter=new MyAdapter(getSupportFragmentManager(), l);
        vp.setAdapter(adapter);

    }

}

package com.example.pagerview_fragment;

import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
*FragmentPagerAdapter是PagerAdapter的子类
*PagerAdapter无法与Fragment结合使用
* @author Administrator
*
*/

public class MyAdapter extends FragmentPagerAdapter{

private List l;
/**
 * 
 * @param fm:Fragment管理器
 * @param l
 */

public MyAdapter(FragmentManager fm,List l) {
    super(fm);
    this.l=l;
}

@Override
public Fragment getItem(int position) {
    return l.get(position);

}

@Override
public int getCount() {
    return l.size();
}

}

你可能感兴趣的:(ViewPager与Fragment结合使用)