ViewPager使用FragmentPagerAdapter在滑动时滞后

时间:2015-11-21 07:24:06

标签: android android-viewpager fragmentpageradapter

我有一个使用FragmentPagerAdapter的ViewPager。我正在使用大小为2048 * 1536的图像在ViewPager中显示。

当我滑动ViewPager时,它有点滞后。 我在这里做错了导致滞后吗?

public class MainActivity extends FragmentActivity {
    static final int NUM_ITEMS = 6;
    ImageFragmentPagerAdapter imageFragmentPagerAdapter;
    ViewPager viewPager;
    public static final String[] IMAGE_NAME = 
    {"image1", "image2", "image3", "image4", "image5", "image6", "image7"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_pager);
        imageFragmentPagerAdapter = 
        new ImageFragmentPagerAdapter(getSupportFragmentManager());
        viewPager = (ViewPager) findViewById(R.id.pager);
        viewPager.setAdapter(imageFragmentPagerAdapter);
    }

    public static class ImageFragmentPagerAdapter extends FragmentPagerAdapter {
        public ImageFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

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

        @Override
        public Fragment getItem(int position) {
            SwipeFragment fragment = new SwipeFragment();
            return SwipeFragment.newInstance(position);
        }
    }

    public static class SwipeFragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View swipeView = inflater.inflate(R.layout.swipe_fragment, container, false);
            ImageView imageView = (ImageView) swipeView.findViewById(R.id.imageView);
            Bundle bundle = getArguments();
            int position = bundle.getInt("position");
            String imageFileName = IMAGE_NAME[position];
            int imgResId = getResources().getIdentifier(imageFileName, "drawable", 
                              "com.viewpager.viewpagerusingfragmentpageradapter");
            imageView.setImageResource(imgResId);
            return swipeView;
        }

        static SwipeFragment newInstance(int position) {
            SwipeFragment swipeFragment = new SwipeFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("position", position);
            swipeFragment.setArguments(bundle);
            return swipeFragment;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

由于您在片段中使用的图片大小,您的ViewPager会停止滑动。缩小图像的大小并将其缩小到片段的大小。这将减少应用程序的内存消耗,ViewPager将停止滞后。

要缩小图像的大小,请更改每个图像的inSampleSize。如果inSampleSize设置为值> gt; 1然后解码器对原始图像进行子采样并返回较小的图像以节省内存。 inSampleSize可以在BitmapFactory.Options

中找到

有关详细信息,请转到以下链接: -

http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

如果您的图片仍然滞后,您可以通过

的帮助进一步缩小图像
Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter) 

方法