Implementing Viewpager For Displaying The Images That Comes From Server
I want to implement viewpager. In my view pager i need to show the images that comes from the Rest API. Please give me necessary suggestions and advice so that i can be successful
Solution 1:
First you need a custom viewpager adapter : Picasso is a great library to load images from. I will give you a link in case you need further help understanding it : http://square.github.io/picasso/
publicclassViewPagerAdapterextendsPagerAdapter {
Context c;
privateList<String> _imagePaths;
privateLayoutInflater inflater;
publicViewPagerAdapter(Context c, List<String> imagePaths) {
this._imagePaths = imagePaths;
this.c = c;
}
@Overridepublic int getCount() {
returnthis._imagePaths.size();
}
@OverridepublicbooleanisViewFromObject(View view, Objectobject) {
return view == (object);
}
@OverridepublicObjectinstantiateItem(ViewGroup container, int position) {
ImageView imgDisplay;
inflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.pager_item, container,
false);
imgDisplay = (ImageView) viewLayout.findViewById(R.id.image);
Picasso.with(c).load(_imagePaths.get(position)).into(imgDisplay);
(container).addView(viewLayout);
return viewLayout;
}
@OverridepublicvoiddestroyItem(ViewGroup container, int position, Objectobject) {
(container).removeView((RelativeLayout) object);
}
}
This is the pager_item.xml :
<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><ImageViewandroid:id="@+id/image"android:layout_centerInParent="true"android:layout_width="match_parent"android:layout_height="match_parent" /></RelativeLayout>
From your activity:
After fetching the list urls from Rest : This is what you do :
List<String> urls;
publicclassMainPageextendsActivity {
publicvoidonCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.main_page);
urls= newArrayList<>();
pager = (ViewPager) findViewById(R.id.pager);
urls.add("www.image1.com");
urls.add("www.image2.com");
pager.setAdapter(newViewPagerAdapter(getApplicationContext(), urls));
}
}
Post a Comment for "Implementing Viewpager For Displaying The Images That Comes From Server"