我需要制作一个像图片库一样工作的小应用程序:我应该使用查看分页器,当用户向左或向右滑动时,应该从网址加载图片。我有一个带网址的数组,当用户滑动到新页面时它应该开始加载特定的图像(它不应该在开始时加载所有图像)。例如,如果我在第一页,我应该看到来自url的第一个图像(数组中的索引0)。当我滑到第二页时,app应该开始从索引1加载图像,如果完成加载,它应该出现在屏幕上。我使用查看寻呼机处理来自资源的图像,但我不能用远程图像来处理它。
我不应该使用任何现有的库,代码或类似的东西。到目前为止,这是我的代码: 主要活动:
urls = new int[] {
R.drawable.i1, R.drawable.i2, R.drawable.i3, R.drawable.i4, R.drawable.i5
};
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new ViewPagerAdapter(MainActivity.this, urls);
viewPager.setAdapter(adapter);
这是我的View适配器:
public ViewPagerAdapter(Context context, int[] urls) {
this.context = context;
this.urls = urls;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container,
false);
// Locate the TextViews in viewpager_item.xml
imgflag = (ImageView) itemView.findViewById(R.id.image);
imgflag.setImageResource(urls[position]);
((ViewPager) container).addView(itemView);
return itemView;
}
layout.viewpager_item.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:padding="10dp" >
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#000000"
android:padding="1dp" />
有任何建议吗?
答案 0 :(得分:2)
您可以使用像Picasso
这样的ImageLoaderPicasso.with(context).load(urls[position]).into(imgflag);
或者:
public class AsynImageLoader extends AsyncTask<Void,Void,Void>{
public String url;
public ImageView img ;
public AsynImageLoader(ImageView img,String url){
this.url = url;
this.img = img;
}
@Override
protected Void doInBackground(Void... params) {
try {
Bitmap bitmap;
URL imageUrl = new URL(url);
HttpURLConnection connection;
if (url.startsWith("https://")) {
connection = (HttpsURLConnection) imageUrl.openConnection();
} else {
connection = (HttpURLConnection) imageUrl.openConnection();
}
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setInstanceFollowRedirects(true);
InputStream is = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
if(img!=null){
img.setImageBitmap(bitmap);
}
}catch(Exception e){
}
return null;
}
}
在你的适配器中你写道:
AsynImageLoader task = new AsynImageLoader(imgflag,urls[position]);
task.execute();