未调用ViewPager onPageScrolled事件

时间:2012-08-17 19:49:26

标签: android android-viewpager

以下代码滚动4页就好了。我的问题是滚动页面时不会触发onPageScrolled事件。无论我是否使用myPager.SetOffsccreenPageLimit(4)命令,都会发生这种情况。阅读文档后,我的理解是,当implements ViewPager.OnPageChangeListener类中包含MyPagerAdapter时,应该触发该事件。我做错了什么?

谢谢, 加里布莱克利

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    MyPagerAdapter adapter = new MyPagerAdapter();
    ViewPager myPager = (ViewPager) findViewById(R.id.mysevenpanelpager);
    myPager.setAdapter(adapter);
    myPager.setCurrentItem(0);
    myPager.setOffscreenPageLimit(4);
}

private class MyPagerAdapter extends PagerAdapter 
    implements ViewPager.OnPageChangeListener {

    public int getCount() {
        return 4;
    }

    public Object instantiateItem(View collection, int position) {
        LayoutInflater inflater = (LayoutInflater) collection.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        int resId = 0;
        switch (position) {
        case 0:
            resId = R.layout.left;
            break;
        case 1:
            resId = R.layout.gps;
            break;
        case 2:
            resId = R.layout.map;
            break;
        case 3:
            resId = R.layout.right;
            break;
        }

        View view = inflater.inflate(resId, null);

        ((ViewPager) collection).addView(view, 0);

        return view;
    }

    @Override
    public void destroyItem(View arg0, int arg1, Object arg2) {
        ((ViewPager) arg0).removeView((View) arg2);
    }
    @Override
    public void onPageScrollStateChanged(int arg0) {
        int myint = 9;
        myint = myint * 2;
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        int myint = 9;
        myint = myint * 2;
    }

    @Override
    public void onPageSelected(int arg0) {
        int myint = 9;
        myint = myint * 2;
    }
}

3 个答案:

答案 0 :(得分:7)

您还需要set使用setOnPageChangeListener() {。}}。{/ p>

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    MyPagerAdapter adapter = new MyPagerAdapter();
    ViewPager myPager = (ViewPager) findViewById(R.id.mysevenpanelpager);
    myPager.setAdapter(adapter);
    myPager.setCurrentItem(0);
    myPager.setOffscreenPageLimit(4);
    myPager.setOnPageChangeListener(adapter); // This line here
}

答案 1 :(得分:1)

我相信您还需要使用ViewPager上的.setOnPageChangeListener()将您的Adapter实例注册为这些类型的事件的监听器。

答案 2 :(得分:0)

您需要设置一个侦听器,但不推荐使用 setOnPageChangeListener(OnPageChangeListener) 。您应该使用 addOnPageChangeListener(OnPageChangeListener) 来代替多个侦听器。