Android viewpager+photoview的使用

可实现多张图片点击放大,手指控制,左右滑动,多张图片点击任意位置定位显示任意位置图片;无动画

Android viewpager+photoview的使用_第1张图片

Android viewpager+photoview的使用_第2张图片

核心代码:

viewpager:

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

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

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        try {
            return super.onInterceptTouchEvent(ev);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return false;
        }
    }

}

adapter:

public class PageAdapter extends PagerAdapter {
    List imagesUrl;
    Context context;

    public PageAdapter(List imagesUrl, Context context) {
        this.imagesUrl = imagesUrl;
        this.context = context;
    }

    @Override
    public int getCount() {
        return (imagesUrl == null || imagesUrl.size() == 0) ? 0 : imagesUrl.size();
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        String url = imagesUrl.get(position);

        PhotoView photoView = new PhotoView(context);
        Glide.with(context)
                .load("http://test.zuihou99.com" + url)
                .into(photoView);
        container.addView(photoView);
        photoView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        return photoView;
    }

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

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

}

activity里有保存图片到本地相册的功能实现代码如下:

public class ImageBigActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    @Bind(R.id.page)
    TextView page;
    @Bind(R.id.top)
    RelativeLayout top;
    @Bind(R.id.viewPager)
    PhotoViewPager viewPager;
    @Bind(R.id.save)
    TextView save;
    ArrayList imagesUrl;
    int current;
    PageAdapter pagerAdapter;

    private static final int REQUEST_CODE_SAVE_IMG = 10;

    @Override
    public int getLayoutId() {
        return R.layout.imagebig_layout;
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {
        if (getIntent() != null) {
            Intent intent = getIntent();
            imagesUrl = intent.getStringArrayListExtra("images");
            current = intent.getIntExtra("position", 0);
        }
        pagerAdapter = new PageAdapter(imagesUrl, getApplicationContext());
        viewPager.setAdapter(pagerAdapter);
        viewPager.setCurrentItem(current);
        page.setText(current + 1 + "/" + imagesUrl.size());
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                current = position;
                page.setText(current + 1 + "/" + imagesUrl.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @OnClick(R.id.save)
    public void save() {
        requestPermission();
    }

    /**
     * 请求读取sd卡的权限
     */
    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            //读取sd卡的权限
            String[] mPermissionList = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (EasyPermissions.hasPermissions(getApplicationContext(), mPermissionList)) {
                //已经同意过
                saveImage();
            } else {
                //未同意过,或者说是拒绝了,再次申请权限
                EasyPermissions.requestPermissions(
                        this,  //上下文
                        "保存图片需要读取sd卡的权限", //提示文言
                        REQUEST_CODE_SAVE_IMG, //请求码
                        mPermissionList //权限列表
                );
            }
        } else {
            saveImage();
        }
    }


    /**
     * 保存图片
     */
    private void saveImage() {
        System.out.println(" 6666 ");
        System.out.println(current + " current ");
        final String urls = imagesUrl.get(current);
        System.out.println(urls + " url ");
        System.out.println(" 8888 ");

//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.fj);

        new Thread(new Runnable() {
            Bitmap bitmap = null;
            @Override
            public void run() {
                URL url = null;
                try {
                    url = new URL("http://test.zuihou99.com" + urls);
                    InputStream is = null;
                    BufferedInputStream bis = null;
                    try {
                        is = url.openConnection().getInputStream();
                        bis = new BufferedInputStream(is);
                        bitmap = BitmapFactory.decodeStream(bis);

                        boolean isSaveSuccess = ImgUtils.saveImageToGallery(getApplicationContext(), bitmap);
                        if (isSaveSuccess) {
                            Looper.prepare();
                            Toast.makeText(getApplicationContext(), "保存图片成功", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        } else {
                            Looper.prepare();
                            Toast.makeText(getApplicationContext(), "保存图片失败,请稍后重试", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    /**
     * 根据图片的url路径获得Bitmap对象
     *
     * @param url
     * @return
     */
    private Bitmap decodeUriAsBitmapFromNet(String url) {
        URL fileUrl = null;
        Bitmap bitmap = null;

        try {
            fileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            HttpURLConnection conn = (HttpURLConnection) fileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    //授权结果,分发下去
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        //跳转到onPermissionsGranted或者onPermissionsDenied去回调授权结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    //同意授权
    @Override
    public void onPermissionsGranted(int requestCode, List list) {
        saveImage();
    }

    //拒绝授权
    @Override
    public void onPermissionsDenied(int requestCode, List perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            //打开系统设置,手动授权
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            //拒绝授权后,从系统设置了授权后,返回APP进行相应的操作
            saveImage();
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}

startActivity跳转代码:

 private void statPhotoViewActivity(int position) {
        Intent intent = new Intent(this, ImageBigActivity.class);
        intent.putStringArrayListExtra("images", imagesList);
        intent.putExtra("position", position);
        startActivity(intent);
    }

activity布局文件:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/top"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:paddingLeft="@dimen/margin_8"
        android:paddingRight="@dimen/margin_8">

        <ImageView
            android:id="@+id/back"
            android:layout_width="15dp"
            android:layout_height="15dp"
            android:layout_centerVertical="true"
            android:onClick="back"
            android:scaleType="centerCrop"
            android:src="@mipmap/ic_image_back" />

        <TextView
            android:id="@+id/page"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text=""
            android:textColor="@color/homepage_type_bg"
            android:textSize="@dimen/font_15" />
    RelativeLayout>

    <com.zuihou.drunkenmonkey.widget.view.PhotoViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/top"
        android:background="#444444" />

    <TextView
        android:id="@+id/save"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:clickable="true"
        android:gravity="right"
        android:paddingRight="@dimen/margin_16"
        android:text="保存"
        android:textColor="@color/homepage_type_bg"
        android:textSize="@dimen/font_16" />
RelativeLayout>

你可能感兴趣的:(ViewPager,photoview)