首先
WebView大家基本都了解了。那么activity_main.xml的代码就太简单了。
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context="com.peng3.big.big.showzoomableimagefromwebview.MainActivity">
<WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
接下来是MainActivity.class的代码。重点在这里。
private WebView mWebView;
private String url;
{
setContentView(R.layout.activity_main);
//就让我更无耻一点吧!
url = "http://www.jianshu.com/p/d614bb028588";
mWebView = (WebView) findViewById(R.id.web_view);
//设置javascript脚步可执行
mWebView.getSettings().setJavaScriptEnabled(true);
//防止中文乱码
mWebView.getSettings().setDefaultTextEncodingName("UTF -8");
//载入js
mWebView.addJavascriptInterface(new JavascriptInterface(this), "imagelistner");
mWebView.setWebViewClient(new WebViewClient() {
// 网页开始加载
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
view.getSettings().setJavaScriptEnabled(true);
super.onPageStarted(view, url, favicon);
}
// 网页跳转
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
// 网页加载结束
@Override
public void onPageFinished(WebView view, String url) {
view.getSettings().setJavaScriptEnabled(true);
super.onPageFinished(view, url);
// html加载完成之后,添加监听图片的点击js函数
addImageClickListner();
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
//出现页面错误的时候,不让webView显示了。同时跳出一个错误Toast
mWebView.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "请检查您的网络设置", Toast.LENGTH_SHORT).show();
}
});
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
}
// 网页标题
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
}
});
mWebView.loadUrl(url);
}
// 注入js函数监听
private void addImageClickListner() {
// 这段js函数的功能就是,遍历所有的img几点,并添加onclick函数,函数的功能是在图片点击的时候调用本地java接口并传递url过去
mWebView.loadUrl("javascript:(function(){" +
"var objs = document.getElementsByTagName(\"img\"); " +
"for(var i=0;i<objs.length;i++) " +
"{"
+ " objs[i].onclick=function() " +
" { "
+ " window.imagelistner.openImage(this.src); " +
" } " +
"}" +
"})()");
}
// js通信接口
public class JavascriptInterface {
private Context context;
public JavascriptInterface(Context context) {
this.context = context;
}
@android.webkit.JavascriptInterface
public void openImage(String img) {
System.out.println(img);
Intent intent = new Intent();
intent.putExtra("image", img);
intent.setClass(context, ShowWebImageActivity.class);
context.startActivity(intent);
System.out.println(img);
}
}
关于显示可放大,缩小的ImageView,我使用了PhotoView(包含下载功能,下载目录为SD卡根目录下的ImagesFromWebView目录里面).
ShowWebImageActivity.class
//获取图片的地址
private String imageUrl = null;
//用户放大,缩小,旋转,
private PhotoView imageView = null;
private ImageButton btnBack;
private Button btnDownload;
private Handler mHandler;
{
super.onCreate(savedInstanceState);
btnBack = (ImageButton) findViewById(R.id.btn_back);
btnBack.setOnClickListener(this);
btnDownload = (Button) findViewById(R.id.btn_download);
btnDownload.setOnClickListener(this);
imageUrl = getIntent().getStringExtra("image");
//photoview
imageView = (PhotoView) findViewById(R.id.show_webimage_imageview);
// 启用图片缩放功能
imageView.enable();
//显示图片
ImageLoaderUtils.displayWhole(this, imageView, imageUrl);
mHandler = new Handler();
}
@Override
protected int getLayoutResId() {
return R.layout.activity_show_webimage;
}
@Override
public void onClick(View view) {
if (view == btnBack) {
finish();
} else if (view == btnDownload) {
Toast.makeText(getApplicationContext(), "开始下载图片", Toast.LENGTH_SHORT).show();
downloadImage();
}
}
/**
* 开始下载图片
*/
private void downloadImage() {
downloadAsyn(imageUrl, Environment.getExternalStorageDirectory().getAbsolutePath() + "/ImagesFromWebView");
}
/**
* 异步下载文件
*
* @param url
* @param destFileDir 本地文件存储的文件夹
*/
private void downloadAsyn(final String url, final String destFileDir) {
OkHttpUtil mOkHttpUtil = OkHttpUtil.getInstance();
OkHttpClient mOkHttpClient = mOkHttpUtil.getOkHttpClient();
final Request request = new Request.Builder()
.url(url)
.build();
final Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(getApplicationContext(), "下载失败,请检查网络设置", Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
try {
is = response.body().byteStream();
File file = new File(destFileDir);
//如果file不存在,就创建这个file
if (!file.exists()) {
file.mkdir();
}
File imageFile = new File(destFileDir, getFileName(url) + ".jpg");
fos = new FileOutputStream(imageFile);
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
//如果下载文件成功,第一个参数为文件的绝对路径
//sendSuccessResultCallback(file.getAbsolutePath(), callback);
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "下载成功", Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.printStackTrace();
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "下载失败,请检查网络设置", Toast.LENGTH_SHORT).show();
}
});
} finally {
try {
if (is != null) is.close();
} catch (IOException e) {
}
try {
if (fos != null) fos.close();
} catch (IOException e) {
}
}
}
});
}
private String getFileName(String path) {
int separatorIndex = path.lastIndexOf("/");
return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length());
}
简书的图片地址最后都是 1240.所以从简书下载的图片都只有一张哦。
最后
最后发现,自己还只是一个功能装配师。好忧伤啊。如果大家有更好的,更优美的,或者还有其他的方式的方法实现,求赐教。
一个未到一年的Android开发菜鸟如是说到。
文/你家鹏大大(简书作者)
原文链接:http://www.jianshu.com/p/e24ee6d67f01
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
原文链接:http://www.jianshu.com/p/e24ee6d67f01
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。