I'm getting all the images from my gallery.(pictures from Samsung galaxy s5)
I can view the images from Viewpager.
But when I start Swiping. Its too Slow.
And after a few seconds, the app crashed without having error in logcat.
public class Paging extends PagerAdapter {
private ArrayList<String> IMAGES = new ArrayList<>();
private Context context;
private LayoutInflater layoutInflater;
public Paging(Context context) {
this.context = context;
}
@Override
public int getCount() {
return MainActivity.IMAGES.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return (view == (LinearLayout) object);
}
@Override
public View instantiateItem(View container, int position) {
IMAGES = (ArrayList<String>) MainActivity.IMAGES.clone();
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.imagepager_layout, (ViewGroup) container, false);
ImageView imageView = (ImageView) item_view.findViewById(R.id.img);
Picasso.with(context)
.load(IMAGES.get(position))
.placeholder(R.drawable.plusbtn)
.into(imageView);
((ViewGroup) container).addView(item_view);
return item_view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
My viewPager adding adapter.
viewPager = (ViewPager)findViewById(R.id.view_pager);
adap = new Paging(MainActivity.this);
viewPager.setAdapter(adap);
My XMLs..
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical">
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:gravity="center" />
</LinearLayout>
My view Pager.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"></android.support.v4.view.ViewPager>
</LinearLayout>
this is most probably caused by loading too much image pixel data than necessary (to fit your view size). if your images are huge in size, Picasso
by default would load full size of the image into memory, leading to both slow frame rate as well as OOM exceptions.
a quick fix would be to use Picasso.with().load().resize(width, height)
. It will enable Picasso
to load a downsampled version of the image into memory. on the UI side, you could use fitCenter
scale type for your ImageView
.
to understand the concept better, though, i would suggest reading more on Google's developer guide on this topic here: Loading Large Bitmaps Efficiently