PagerAdapter在第一次转换中变慢

时间:2014-09-26 17:34:20

标签: android android-viewpager

我有一个ViewPager和一个PagerAdapter,它从远程服务器(通过他们的id)下载一些图像并显示它们。它几乎完美地工作,除了从第一页到第二页滑动时,它有点慢(如1秒),而之后的所有其他转换都是正常的。这不是一个网络问题,因为即使我在刷卡之前等了很多,问题仍然存在。 有关为什么会发生这种情况的任何想法?

这是我的代码:

public class SliderAdapter extends PagerAdapter{

private SliderActivity activity;
private long[] imageIds;
private LayoutInflater inflater;
private List<Bitmap> images = new ArrayList<Bitmap>();

public SliderAdapter(Activity activity,
        long[] imageIds) {
    this.activity = (SliderActivity) activity;
    this.imageIds = imageIds;
    for (int i=0; i<imageIds.length; i++){
        new GetImageTask(imageIds[i]).execute();

    }
}

@Override
public int getCount() {
    return imageIds.length;
}

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

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

    inflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container,
            false);

    imgDisplay = (ImageView) viewLayout.findViewById(R.id.imgDisplay);

    if (images.size()-1 >= position && images.get(position) != null)
        imgDisplay.setImageBitmap(images.get(position));


    ((ViewPager) container).addView(viewLayout);


    return viewLayout;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    ((ViewPager) container).removeView((RelativeLayout) object);

}

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}

private class GetImageTask extends AsyncTask<Void, Void, Bitmap> {

    private final String LOG_TAG = GetImageTask.class.getName();

    private Long id;

    public GetImageTask(Long id) {          
        super();
        this.id = id;
    }

    @Override
    protected Bitmap doInBackground(Void... params) {

        //Download image code
    }

    @Override
    protected void onPostExecute(Bitmap imgBmp) {
        if (imgBmp!=null) {

            images.add(imgBmp);
            activity.adapter.notifyDataSetChanged();

        }
    }
}

}

3 个答案:

答案 0 :(得分:1)

问题可能是由于图像..请阅读此处以优化图像 http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

但是,如果您仍然遇到问题,请阅读http://developer.android.com/training/improving-layouts/smooth-scrolling.html

答案 1 :(得分:1)

最后,这是一个过度分辨图像的问题,这会在加载图像时造成缓慢。添加像

这样的东西就足够了
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDensity = 5;
options.inTargetDensity = 2;
Bitmap imgBmp = BitmapFactory.decodeByteArray(imgArray, 0,
                imgArray.length, options);

解码图像时降低分辨率,并且viewpager突然变得平滑。

答案 2 :(得分:0)

尝试使用毕加索组件处理图像。它可以帮助您,因为它可以缓存图像。

您可以在此处找到它:http://square.github.io/picasso/