ViewPager事件destroyItem非常慢

时间:2016-06-09 03:09:35

标签: android android-viewpager

我在ViewPager上测试了onPageSelecteddestroyItem之间的时间,我发现它非常慢。选择页面后,平均花费200-700毫秒来触发destroyItem事件,这是我的代码:

private ViewPager mViewPager;
private GestureDetector mGestureDetector;
private ViewPagerAdapter mAdapter;
private ViewPagerChangeListener mChangeListener;
private long time;

int[] resources = {
        R.mipmap.ic_launcher,
        R.mipmap.ic_launcher,
        R.mipmap.ic_launcher,
        R.mipmap.ic_launcher,
        R.mipmap.ic_launcher,
        R.mipmap.ic_launcher
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Get the ViewFlipper
    mViewPager = (ViewPager) findViewById(R.id.viewPager);
    mChangeListener = new ViewPagerChangeListener();
    mViewPager.addOnPageChangeListener(mChangeListener);
    mAdapter = new ViewPagerAdapter();
    mViewPager.setAdapter(mAdapter);

}

class ViewPagerAdapter extends PagerAdapter{


    @Override
    public int getCount() {
        return 1000;
    }

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

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        Log.d("Time", "paging being instantiate:" + (System.currentTimeMillis() - time));
        ImageView view = new ImageView(getApplicationContext());
        int p = position;
        if(p > 5)
            p = 5;
        view.setImageResource(resources[p]);

        container.addView(view, 0);
        Log.d("Time", "paging after instantiated:" + (System.currentTimeMillis() - time));
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {

        Log.d("Time", "paging being destroy:" + (System.currentTimeMillis() - time));
        container.removeView((ImageView)object);
        Log.d("Time", "paging after destroyed:" + (System.currentTimeMillis() - time));
    }
}

class ViewPagerChangeListener implements android.support.v4.view.ViewPager.OnPageChangeListener {

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

        time = System.currentTimeMillis();
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}

以下是我请求正确页面时的测试结果(请求左页面时,instantiateItem事件将在destroyItem事件之前调用)

paging being destroy:639
paging after destroyed:640
paging being instantiate:640
paging after instantiated:641

问题是,有没有办法强制寻呼机适配器调用事件比正常情况更快地销毁?

0 个答案:

没有答案