6

以下代码可以很好地滚动 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;
    }
}
4

3 回答 3

7

您还需要set使用setOnPageChangeListener().

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
}
于 2012-08-17T19:54:45.770 回答
1

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

于 2012-08-17T19:56:30.887 回答
0

您需要设置一个侦听器,但setOnPageChangeListener(OnPageChangeListener)已弃用。您应该使用addOnPageChangeListener(OnPageChangeListener)能够拥有多个侦听器。

于 2017-10-17T07:50:12.980 回答