如何将片段添加到ViewPager?

时间:2013-08-15 10:53:33

标签: android android-fragments android-viewpager

我有一个SplashScreen,它是一个ViewPager,我需要在它上面添加Login Fragment。

这是我的PagerAdapter:

public class SplashSAdapter extends PagerAdapter {

    Context ssContext;
    Activity _activity;
    private int[] ssImages = new int[] { R.drawable.splashscreen1,R.drawable.splashscreen2, R.drawable.splashscreen3 };

    public SplashSAdapter(Context ssContext, Activity activity) {
        this.ssContext = ssContext;
        this._activity = activity;
    }

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

    @Override
    public boolean isViewFromObject(View ssView, Object ssObject) {
        return ssView == ((ImageView) ssObject);
    }

    @Override
    public Object instantiateItem(ViewGroup ssContainer, int ssPosition) {
        ImageView ssImageView = new ImageView(ssContext);
        ssImageView.setScaleType(ImageView.ScaleType.FIT_XY);
        ssImageView.setImageResource(ssImages[ssPosition]);
        ((ViewPager) ssContainer).addView(ssImageView, 0);
        ssImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                onClickSplashScreen();
            }
        });

        return ssImageView;
    }

    @Override
    public void destroyItem(ViewGroup ssContainer, int ssPosition,
            Object ssObject) {
        ((ViewPager) ssContainer).removeView((ImageView) ssObject);
    }

    public void onClickSplashScreen(){
}

那么,onClickSplashScreen,如何在那里添加片段?

2 个答案:

答案 0 :(得分:0)

您应该使用FragmentPagerAdapter而不是PagerAdapter,

可在此处找到示例 http://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html

答案 1 :(得分:-1)

FragmentManager fragmentManager = this._activity.getSupportFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

这对你有帮助吗?