Android : ViewPager scroll lagging in Android

on Saturday, April 18, 2015


I am using a ViewPager to show various GridViews with a set of images for each one. enter image description here


I just copy and pasted all the images to the drawables folder and they had 300px X 300px each, when swiping between the different grids the swipe lagged a lot, I tried resizing the images to half the size, it got better but the problem persists.


Then I tried to load each image using an AsyncTask like this:



public class ImageAdapter extends BaseAdapter {
private Context mContext;
private Integer[] mSeries;

public ImageAdapter(Context c, int n) {
super();
this.mContext = c;
this.mSeries = ArrayImages.getImages(n);
}

public int getCount() {
return mSeries.length;
}

public Object getItem(int position) {
return null;
}

public long getItemId(int position) {
return 0;
}

// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}

imageView.setDrawingCacheEnabled(true);
new LoadImage(imageView, position).execute();
return imageView;
}

class LoadImage extends AsyncTask<Object, Void, Integer> {

private ImageView imv;
private int position;

public LoadImage(ImageView imv, int pos) {
this.imv = imv;
this.position = pos;
}

@Override
protected Integer doInBackground(Object... params) {
return mSeries[position];
}
@Override
protected void onPostExecute(Integer result) {
if(result != 0 && imv != null){
imv.setVisibility(View.VISIBLE);
imv.setImageResource(result);
}else{
imv.setVisibility(View.GONE);
}
}
}


But the problem still persists and since there are a 250 images I made some arrays to keep them all and when I need them I just ask: ArrayImages.getImages(n) not sure if this might be the problem.


Since my FragmentPagerAdapter has to create all the 16 GridFragment and get those arrays:



public class ViewPagerAdapter extends FragmentStatePagerAdapter {

private int NumbOfTabs = 16; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created


// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}

//This method return the fragment for the every position in the View Pager
@Override
public Fragment getItem(int index) {
// TODO Auto-generated method stub
switch (index) {
case 0:
return new GridFragment(1);

case 1:
return new GridFragment(2);
...
case 16:
return new GridFragment(16);


What can I do to improve the loading and remove the lag?


0 comments:

Post a Comment