0

我正在使用 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;
    }

}

我的寻呼机适配器:

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。

谢谢!

4

1 回答 1

0

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

Fragment getItem(int position){}

与你的片段

return getNewInstance();

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

于 2013-01-07T22:19:38.107 回答