实现ViewPager以显示来自服务器的图像 [英] Implementing ViewPager for displaying the images that comes from server
问题描述
我想实现viewpager.在我的视图寻呼机中,我需要显示来自Rest API的图像.请给我必要的建议,以便我可以成功地做到这一点.
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 in that.
推荐答案
首先,您需要一个自定义的viewpager适配器: 毕加索(Picasso)是一个出色的库,可从中加载图像.如果您需要进一步的帮助以了解它,我会给您一个链接: http://square.github.io/picasso /
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/
public class ViewPagerAdapter extends PagerAdapter {
Context c;
private List<String> _imagePaths;
private LayoutInflater inflater;
public ViewPagerAdapter(Context c, List<String> imagePaths) {
this._imagePaths = imagePaths;
this.c = c;
}
@Override
public int getCount() {
return this._imagePaths.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == (object);
}
@Override
public Object instantiateItem(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;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
(container).removeView((RelativeLayout) object);
}
}
这是pager_item.xml:
This is the pager_item.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/image"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
根据您的活动:
从Rest中获取列表网址后:这就是您要做的事情:
After fetching the list urls from Rest : This is what you do :
List<String> urls;
public class MainPage extends Activity {
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.main_page);
urls= new ArrayList<>();
pager = (ViewPager) findViewById(R.id.pager);
urls.add("www.image1.com");
urls.add("www.image2.com");
pager.setAdapter(new ViewPagerAdapter(getApplicationContext(), urls));
}
}
这篇关于实现ViewPager以显示来自服务器的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!