android – 未调用ViewPager onPageScrolled事件

前端之家收集整理的这篇文章主要介绍了android – 未调用ViewPager onPageScrolled事件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
下面的代码滚动4页就好了.我的问题是滚动页面时不会触发onPageScrolled事件.无论我是否使用myPager.SetOffsccreenPageLimit(4)命令,都会发生这种情况.阅读文档之后,我理解当我实现MyPagerAdapter类中包含的ViewPager.OnPageChangeListener时,应该触发事件.我究竟做错了什么?

谢谢,
加里布莱克利

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;
    }
}

解决方法

您还需要使用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
}
原文链接:https://www.f2er.com/android/309192.html

猜你在找的Android相关文章