WebView 点击查看大图

在日常的开发中,我们经常会用webView加载网页显示页面效果。在有些时候网页中的图片我们需要点击放大,今天我就记录一下实现过程。

需要用到的点

  1. 获取网页中所有的图片;
  2. 捕获所有图片并且设置点击事件;
  3. 支持查看上下一张图片、图片放大;
  4. 图片长按保存;
  5. 图片缓存处理。

前期准备

权限







依赖

// 支持双指拖动放大的ImageView
compile 'com.bm.photoview:library:1.4.1'
//Glide 图片加载框架
compile 'com.github.bumptech.glide:glide:3.7.0'

从网页到图片浏览界面我们首先是需要获取到图片。可以在接口返回网页地址的时候,把其中的图片网址一块返回。也可以在加载网页的时候获取所有的图片资源,当然这种方式可能因为有一些不需要浏览界面显示的图片也获取到。选择哪一种方式,就根据实际情况来吧。

包含WebView的Activtity代码很简单

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.getSettings().setDatabaseEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.loadUrl("https://mparticle.uc.cn/article.html?uc_param_str=frdnsnpfvecpntnwprdssskt&client=ucweb&wm_id=5bc2ee183eeb442583312b991a5bb40c&title_type=1&pagetype=share&app=uc-iflow&btifl=100&wm_cid=282746943169101824&wm_aid=46c53cb248374dc1aa0f4623fab66f57&uc_share_depth=1");
        //mWebView.addJavascriptInterface(new MyJavaScripteInterface(this,imageUrls),"imagelistener");//方法一  后台直接返回
       mWebView.addJavascriptInterface(new MyJavaScripteInterface(this),"imagelistener");
        mWebView.setWebViewClient(new MyWebViewClient());
    }

就是给WebView做了一些初始化的操作,自定义MyJavaScripteInterface类处理js调用本地方法,自定义MyWebViewClient实现对WebView的监听管理

MyWebViewClient代码如下

  public class MyWebViewClient extends WebViewClient{
    @Override
    public void onPageFinished(WebView view, String url) {
        view.getSettings().setJavaScriptEnabled(true);
        super.onPageFinished(view, url);
        addImageClickListener(view);//待网页加载完全后设置图片点击的监听方法
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        view.getSettings().setJavaScriptEnabled(true);
        super.onPageStarted(view, url, favicon);
    }

    private void addImageClickListener(WebView webView) {
        webView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                " var array=new Array(); " +
                " for(var j=0;j

自定义WebViewClient,在onPageFinished方法中设置addImageClickListener的监听方法,当整个WebView页面加载完毕后,为每张图片设置监听事件。这意味着,整个页面未加载完毕时,点击是无效的。
addImageClickListener的代码实现也很简单,通过js找到相应的img标签,这样就知道是图片了,可以把所有的图片资源获取到放入数组当中,然后为这些图片设置点击监听事件。每当点击时调用自定义的openImage()方法。这个openImage()方法与MJavascriptInterface中对应的方法对应,这样就形成了js调用本地的方法。

MJavascriptInterface代码(主要为js对应的本地方法的实现):

public class MyJavaScripteInterface {
    private Context context;
    private String [] imageUrls;

    public MyJavaScripteInterface(Context context,String[] imageUrls) {
        this.context = context;
        this.imageUrls = imageUrls;
    } 
    public MyJavaScripteInterface(Context context) {
        this.context = context;
    }

    /**
     * 接口返回的方式
     */
    @android.webkit.JavascriptInterface
    public void openImage(String img,String[] imageUrls) {
        Intent intent = new Intent();
        intent.putExtra("imageUrls", imageUrls);
        intent.putExtra("curImageUrl", img);
        intent.setClass(context, PhotoBrowserActivity.class);
        context.startActivity(intent);
        for (int i = 0; i < imageUrls.length; i++) {
            Log.e("图片地址"+i,imageUrls[i].toString());
        }
    }

    /**
     * 加载时获取资源的方式
     */
    @android.webkit.JavascriptInterface
    public void openImage(String img) {
        Intent intent = new Intent();
        intent.putExtra("imageUrls", imageUrls);
        intent.putExtra("curImageUrl", img);
        intent.setClass(context, PhotoBrowserActivity.class);
        context.startActivity(intent);
        for (int i = 0; i < imageUrls.length; i++) {
            Log.e("图片地址"+i,imageUrls[i].toString());
        }
    }
}

自定义JavascriptInterface中openImage() 方法把当前点击的图片和所有的图片传入到PhotoBrowserActivity中,PhotoBrowserActivity页面是用来显示大图的页面。

到此我们已经将所有图片以及点击图片获取到并且传入到了图片展示页面了,接下来就是做图片显示、放大、浏览等工作了。

PhotoBrowserActivity的布局




    

    

    

    

    


剩下的逻辑都是在PhotoBrowserActivity中完成

图片用ViewPager做显示、浏览,用PhotoView做图片的放大。
mPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return imageUrls.length;
            }
            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }
            @Override
            public Object instantiateItem(ViewGroup container, final int position) {
                //如果当前图片地址不是空就创建一个PhotoView显示图片
                if (imageUrls[position] != null && !"".equals(imageUrls[position])) {
                    final PhotoView view = new PhotoView(PhotoBrowserActivity.this);
                    view.enable();
                    view.setScaleType(ImageView.ScaleType.FIT_CENTER);
                    Glide.with(PhotoBrowserActivity.this)
                            .load(imageUrls[position])
                            .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                            .fitCenter().crossFade()
                            .listener(new RequestListener() {
                                @Override
                                public boolean onException(Exception e, String model, Target target, boolean isFirstResource) {
                                      //图片加载失败
                                       if (position == curPosition) {
                                             hideLoadingAnimation();
                                       }
                                      showErrorLoading();
                                      return false;
                                }

                                @Override
                                public boolean onResourceReady(GlideDrawable resource, String model, Target target, boolean isFromMemoryCache, boolean isFirstResource) {
                                        //图片加载成功
                                        occupyOnePosition(position);
                                        if (position == curPosition) {
                                            hideLoadingAnimation();
                                        }
                                        return false;
                                }
                    }).into(view);
                    view.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            //长按保存图片
                            savePhotoToLocal();
                            return false;
                        }
                    });
                    view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //点击关闭
                            finish();
                        }
                    });
                    container.addView(view);
                    return view;
                }
                return null;
            }


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

            @Override
            public void setPrimaryItem(ViewGroup container, int position, Object object) {
                curPage = (View) object;
            }
        });

PagerAdapter中主要是instantiateItem()方法。
1、创建PhotoView 用来显示图片、图片放大功能。
2、用Glide加载图片,并且设置图片加载的监听
在onException做处理--->取消加载动画效果,显示加载失败图片
onResourceReady做处理--->初始当前位置信息,取消加载动画效果

        //判断点击图片的位置,设置viewpager显示位置
        curPosition = returnClickedPosition() == -1 ? 0 : returnClickedPosition();
        mPager.setCurrentItem(curPosition);
        mPager.setTag(curPosition);
        if (initialedPositions[curPosition] != curPosition) {//如果当前页面未加载完毕,则显示加载动画,反之相反;
            showLoadingAnimation();
        }
        mPhotoOrderTv.setText((curPosition + 1) + "/" + imageUrls.length);//设置页面的编号
        mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }
            @Override
            public void onPageSelected(int position) {
                if (initialedPositions[position] != position) {//如果当前页面未加载完毕,则显示加载动画,反之相反;
                    showLoadingAnimation();
                } else {
                    hideLoadingAnimation();
                }
                curPosition = position;
                mPhotoOrderTv.setText((position + 1) + "/" + imageUrls.length);//设置页面的编号
                mPager.setTag(position);//为当前view设置tag
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

1.首先通过returnClickedPosition方法来获得用户点击的是哪一张图片的位置并设置当前是哪一个page;
2.通过addOnPageChangeListener来实现对页面滑动事件的监听——>此处主要用来处理设置当前页面的position、动画、页面序号显示的逻辑;

图片保存的代码

private void savePhotoToLocal() {
        PhotoView photoViewTemp = (PhotoView) curPage;
        if (photoViewTemp != null) {
            GlideBitmapDrawable glideBitmapDrawable = (GlideBitmapDrawable) photoViewTemp.getDrawable();
            if (glideBitmapDrawable == null) {
                return;
            }
            Bitmap bitmap = glideBitmapDrawable.getBitmap();
            if (bitmap == null) {
                return;
            }
            FileUtils.savePhoto(this, bitmap, new FileUtils.SaveResultCallback() {
                @Override
                public void onSavedSuccess() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(PhotoBrowserActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                @Override
                public void onSavedFailed() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(PhotoBrowserActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
        }
    }

根据viewPager位置获取对应位置bitmap,然后将bitmap保存到本地,主要是调用了FileUtils工具类进行图片的保存。

FileUtils工具类

public class FileUtils {
    public static void savePhoto(final Context context, final Bitmap bmp, final SaveResultCallback saveResultCallback) {
        final File sdDir = getSDPath();
        if (sdDir == null) {
            Toast.makeText(context,"设备自带的存储不可用",Toast.LENGTH_LONG).show();
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                File appDir = new File(sdDir, "out_photo");
                if (!appDir.exists()) {
                    appDir.mkdir();
                }
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置以当前时间格式为图片名称
                String fileName = df.format(new Date()) + ".png";
                File file = new File(appDir, fileName);
                try {
                    FileOutputStream fos = new FileOutputStream(file);
                    bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    fos.flush();
                    fos.close();
                    saveResultCallback.onSavedSuccess();
                } catch (FileNotFoundException e) {
                    saveResultCallback.onSavedFailed();
                    e.printStackTrace();
                } catch (IOException e) {
                    saveResultCallback.onSavedFailed();
                    e.printStackTrace();
                }

                //保存图片后发送广播通知更新数据库
                Uri uri = Uri.fromFile(file);
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            }
        }).start();
    }


    public static File getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir;
    }

    public interface SaveResultCallback {
        void onSavedSuccess();

        void onSavedFailed();
    }
}

文件保存,然后通知数据库更新。

PhotoBrowserActivity的全部代码

public class PhotoBrowserActivity extends AppCompatActivity {

    @BindView(R.id.pager)
    ViewPager mPager;
    @BindView(R.id.crossIv)
    ImageView mCrossIv;
    @BindView(R.id.photoOrderTv)
    TextView mPhotoOrderTv;
    @BindView(R.id.saveTv)
    TextView mSaveTv;
    @BindView(R.id.centerIv)
    ImageView mCenterIv;

    private int curPosition = -1;
    private int[] initialedPositions = null;
    private String[] imageUrls;
    private String curImageUrl;
    private ObjectAnimator objectAnimator;
    private View curPage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_photo_browser);
        ButterKnife.bind(this);
        imageUrls = getIntent().getStringArrayExtra("imageUrls");
        curImageUrl = getIntent().getStringExtra("curImageUrl");
        initialedPositions = new int[imageUrls.length];
        initInitialedPositions();
        mPager.setPageMargin((int) (getResources().getDisplayMetrics().density * 15));
        mPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return imageUrls.length;
            }


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

            @Override
            public Object instantiateItem(ViewGroup container, final int position) {
                if (imageUrls[position] != null && !"".equals(imageUrls[position])) {
                    final PhotoView view = new PhotoView(PhotoBrowserActivity.this);
                    view.enable();
                    view.setScaleType(ImageView.ScaleType.FIT_CENTER);
                    Glide.with(PhotoBrowserActivity.this).load(imageUrls[position]).override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).fitCenter().crossFade().listener(new RequestListener() {
                        @Override
                        public boolean onException(Exception e, String model, Target target, boolean isFirstResource) {
                            if (position == curPosition) {
                                hideLoadingAnimation();
                            }
                            showErrorLoading();
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(GlideDrawable resource, String model, Target target, boolean isFromMemoryCache, boolean isFirstResource) {
                            occupyOnePosition(position);
                            if (position == curPosition) {
                                hideLoadingAnimation();
                            }
                            return false;
                        }
                    }).into(view);
                    view.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            savePhotoToLocal();
//                            Toast.makeText(PhotoBrowserActivity.this, "changannananan", Toast.LENGTH_SHORT).show();
                            return false;
                        }
                    });
                    view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
                    container.addView(view);
                    return view;
                }
                return null;
            }


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

            @Override
            public void setPrimaryItem(ViewGroup container, int position, Object object) {
                curPage = (View) object;
            }
        });
        curPosition = returnClickedPosition() == -1 ? 0 : returnClickedPosition();
        mPager.setCurrentItem(curPosition);
        mPager.setTag(curPosition);
        if (initialedPositions[curPosition] != curPosition) {//如果当前页面未加载完毕,则显示加载动画,反之相反;
            showLoadingAnimation();
        }
        mPhotoOrderTv.setText((curPosition + 1) + "/" + imageUrls.length);//设置页面的编号
        mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (initialedPositions[position] != position) {//如果当前页面未加载完毕,则显示加载动画,反之相反;
                    showLoadingAnimation();
                } else {
                    hideLoadingAnimation();
                }
                curPosition = position;
                mPhotoOrderTv.setText((position + 1) + "/" + imageUrls.length);//设置页面的编号
                mPager.setTag(position);//为当前view设置tag
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @OnClick({R.id.crossIv, R.id.saveTv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.crossIv:
                finish();
                break;
            case R.id.saveTv:
                savePhotoToLocal();
                break;
        }
    }



    private void showLoadingAnimation() {
        mCenterIv.setVisibility(View.VISIBLE);
        mCenterIv.setImageResource(R.drawable.loading);
        if (objectAnimator == null) {
            objectAnimator = ObjectAnimator.ofFloat(mCenterIv, "rotation", 0f, 360f);
            objectAnimator.setDuration(2000);
            objectAnimator.setRepeatCount(ValueAnimator.INFINITE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                objectAnimator.setAutoCancel(true);
            }
        }
        objectAnimator.start();
    }
    private void hideLoadingAnimation() {
        releaseResource();
        mCenterIv.setVisibility(View.GONE);
    }
    private void showErrorLoading() {
        mCenterIv.setVisibility(View.VISIBLE);
        releaseResource();
        mCenterIv.setImageResource(R.drawable.load_error);
    }
    private void releaseResource() {
        if (objectAnimator != null) {
            objectAnimator.cancel();
        }
        if (mCenterIv.getAnimation() != null) {
            mCenterIv.getAnimation().cancel();
        }
    }

    private int returnClickedPosition() {
        if (imageUrls == null || curImageUrl == null) {
            return -1;
        }
        for (int i = 0; i < imageUrls.length; i++) {
            if (curImageUrl.equals(imageUrls[i])) {
                return i;
            }
        }
        return -1;
    }


    private void occupyOnePosition(int position) {
        initialedPositions[position] = position;
    }




    private void releaseOnePosition(int position) {
        initialedPositions[position] = -1;
    }



    private void initInitialedPositions() {
        for (int i = 0; i < initialedPositions.length; i++) {
            initialedPositions[i] = -1;
        }
    }
    private void savePhotoToLocal() {
        PhotoView photoViewTemp = (PhotoView) curPage;
        if (photoViewTemp != null) {
            GlideBitmapDrawable glideBitmapDrawable = (GlideBitmapDrawable) photoViewTemp.getDrawable();
            if (glideBitmapDrawable == null) {
                return;
            }
            Bitmap bitmap = glideBitmapDrawable.getBitmap();
            if (bitmap == null) {
                return;
            }
            FileUtils.savePhoto(this, bitmap, new FileUtils.SaveResultCallback() {
                @Override
                public void onSavedSuccess() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(PhotoBrowserActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                @Override
                public void onSavedFailed() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(PhotoBrowserActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
        }
    }

}

关闭页面后缓存的处理

    @Override
    protected void onDestroy() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Glide.get(MainActivity.this).clearDiskCache();//清理磁盘缓存需要在子线程中执行
            }
        }).start();
        Glide.get(this).clearMemory();//清理内存缓存可以在UI主线程中进行
        super.onDestroy();
    }

把这一部分内容加到MainActivity中,在退出应用是清除Glide中的缓存。

注意:在6.0以后需要做动态权限的适配

本文参考https://blog.csdn.net/ganshenml/article/details/55050983

你可能感兴趣的:(WebView 点击查看大图)