目前项目中需要用到ViewPager加载图片,现在在此记录一下。
首先先看布局文件:activity_main.xml
MainActivity
package com.example.fly.viewpagerbanner;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener,View.onClickListener {
private ViewPager vp;
private ViewPagerAdapter vpAdapter;
private List
ViewPagerAdapter
package com.example.fly.viewpagerbanner;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.util.List;
import java.util.Map;
public class ViewPagerAdapter extends PagerAdapter {
Context context;
List> viewLists;
public ViewPagerAdapter(List> lists, Context context) {
this.viewLists = lists;
this.context = context;
}
@Override
public int getCount() { //获得size
return viewLists.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void destroyItem(ViewGroup view, int position, Object object) { //销毁Item
ImageView x = (ImageView) viewLists.get(position).get("view");
x.setScaleType(ImageView.ScaleType.FIT_CENTER);
view.removeView(x);
}
@Override
public Object instantiateItem(ViewGroup view, int position){ //实例化Item
ImageView imageView = (ImageView) viewLists.get(position).get("view");
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
Glide.with(context)
.load(viewLists.get(position).get("url").toString())
// .placeholder(R.mipmap.new_default)
.error(R.mipmap.ic_launcher)
.diskCacheStrategy(DiskCacheStrategy.RESULT)
.into(imageView);
view.addView(imageView, 0);
return viewLists.get(position).get("view");
}
}
是不是很简单。
最后附上demo:http://xiazai.jb51.net/201701/yuanma/ViewPager(jb51.net).rar
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。