PhotoView的简单使用方法

现在基本上上所有的图片点进去都会有放大和缩小的功能,并且可以自由的滑动,其实实现这种功能所使用的photoview写起来也是很简单的。

首先我们需要添加一个photoview的依赖

compile 'com.github.chrisbanes.photoview:library:1.2.4'
依赖添加进去之后就可以写代码,首先我们先自定义一个viewpager

public class HackyViewPager extends ViewPager {
   
    public HackyViewPager(Context context) {
        super(context);
    }

    public HackyViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
      try {
         return super.onInterceptTouchEvent(ev);
      } catch (IllegalArgumentException e) {
         return false;
      }
    }
}
之后就是在布局里面使用我们自定义的一个HackyViewPager,布局文件就不粘贴了。。

接下来就是我们Activity的代码了,同样是很简单的几行

public class MainActivity extends AppCompatActivity {

    private HackyViewPager hvpPhoto;
    private List images;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        hvpPhoto= (HackyViewPager) findViewById(R.id.hvp_photo);
        images=new ArrayList<>();
        images.add("http://pic.jj20.com/up/allimg/1011/05241G14F4/1F524114F4-6.jpg");
        images.add("http://attach.bbs.miui.com/forum/201308/19/120939b33n3ufz02tlttci.jpg");
        images.add("http://pic.jj20.com/up/allimg/1011/05241G14F4/1F524114F4-4.jpg");
        images.add("http://www.pp3.cn/uploads/201505/2015052111.jpg");

        hvpPhoto.setAdapter(new PagerAdapter() {
                @Override
                public Object instantiateItem(ViewGroup container, int position) {
                    PhotoView photoView=new PhotoView(container.getContext());
                    Glide.with(container.getContext()).load(images.get(position)).into(photoView);
                    container.addView(photoView);
                    return photoView;
                }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((View) object);

            }

            @Override
            public int getCount() {
                return images.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view==object;
            }
        });
    }
}


你可能感兴趣的:(PhotoView的简单使用方法)