如何将Fragment作为视图添加到ViewPager?

时间:2013-01-07 22:09:06

标签: android fragment viewpagerindicator fragmentpageradapter

我正在使用viewPager,并希望为其添加片段:

public class MyFragment extends Fragment {
       public View onCreateView(LayoutInflater inflater, ViewGroup contner,
       Bundle savedInstanceState) {
       View view = inflater.inflate(R.layout.tab_frag2_layout, container, false);

        return view;
    }
    public static Fragment newInstance() {
        // TODO Auto-generated method stub
        MyFragment mfg = new MyFragment();
        return mfg;
    }

}

我的PagerAdapter:

public class ViewPagerAdapter extends PagerAdapter 
{

    private static String[] titles = new String[]
    {
        "Page 1",
        "Page 2",
        "Page 3",
        "Page 4"
    };
    private final Context context;

    public ViewPagerAdapter( Context context )
    {
        this.context = context;
    }

    @Override
    public String getPageTitle( int position )
    {
        return titles[ position ];
    }

    @Override
    public int getCount()
    {
        return titles.length;
    }

    @Override
    public Object instantiateItem( View pager, int position )
    {
        TextView v = new TextView( context );
        v.setText( titles[ position ] );
        ((ViewPager)pager).addView( v, 0 );

        //This gives me nullPointerException///////////////////////////////////

        MyFragment mfg = new MyFragment();
        ((ViewPager)pager).addView(mfg.newInstance().getView());

        return v;
    }

    @Override
    public void destroyItem( View pager, int position, Object view )
    {
        ((ViewPager)pager).removeView( (TextView)view );
    }

    @Override
    public boolean isViewFromObject( View view, Object object )
    {
        return view.equals( object );
    }

    @Override
    public void finishUpdate( View view ) {}

    @Override
    public void restoreState( Parcelable p, ClassLoader c ) {}

    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public void startUpdate( View view ) {}
}

将MyFragment添加到ViewPager的正确方法是什么?我必须将它添加为视图,所以我使用newInstance()方法,但给了我一个nullPointerException。

谢谢!

1 个答案:

答案 0 :(得分:0)

使用FragmentPagerAdapter(不是ViewPagerAdapter)并实现其

Fragment getItem(int position){}

使用您的碎片

return getNewInstance();

并且也不要忘记从FragmentActivity类派生您的活动