WebView加载Html文本图片自适应手机屏幕,图片可查(三方依赖)
前言:我们在开发的时候,后台有时候会给我们Html的文本,和图片,但Html一般是电脑端的,放在手机端图片会特别大,所以我们要进行一些适配
先看一下效果
这里因为要用到图片查看器,所以加上以下依赖 ,支持手势双击,单机
//图片选择控件
implementation'com.github.chrisbanes.photoview:library:1.2.4'
先获取到布局里面的WebView进行一些设置,此webview是你自己布局里面的
WebSettings webSettings = webview.getSettings();//获取webview设置属性
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//把html中的内容放大webview等宽的一列中
webSettings.setJavaScriptEnabled(true);//支持js
webSettings.setBuiltInZoomControls(true); // 显示放大缩小
webSettings.setSupportZoom(true); // 可以缩放
此用法设计到js,所以代码中一定要添加这句话
webSettings.setJavaScriptEnabled(true);//支持js
因为要实现点击图片查看功能,给webview重新设置WebViewClient
loadDataWithBaseURL要解析的Html文本
webview.setWebViewClient(new MyWebViewClient());
//这个是给图片设置点击监听的,如果你项目需要webview中图片,点击查看大图功能,可以这么添加
webview.addJavascriptInterface(new JavaScriptInterface(this), "imagelistner");
webview.loadDataWithBaseURL(null, result.getContent(), "text/html", "utf-8", null);
重写WebViewClient的onPageFinished方法
此类直接可直接写成activity的内部类方便使用
private class MyWebViewClientextends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
imgReset(view);//重置webview中img标签的图片大小
// html加载完成之后,添加监听图片的点击js函数
addImageClickListner(view);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// view.loadUrl(url);
return true;
}
/**
* 对图片进行重置大小,宽度就是手机屏幕宽度,高度根据宽度比便自动缩放
*
* @param view
*/
private void imgReset(WebView view) {
view.loadUrl("javascript:(function(){" +
"var objs = document.getElementsByTagName('img'); " +
"for(var i=0;i<objs.length;i++) " +
"{"
+"var img = objs[i]; " +
" img.style.maxWidth = '100%'; img.style.height = 'auto'; " +
"}" +
"})()");
}
/**
* 这段js函数的功能就是,遍历所有的img节点,并添加onclick函数,
* <p>* 函数的功能是在图片点击的时候调用本地java接口并传递url过去
*
* @param view
*/
private void addImageClickListner(WebView view) {
view.loadUrl("javascript:(function(){" +
"var objs = document.getElementsByTagName(\"img\"); " +
"for(var i=0;i<objs.length;i++) " +
"{"
+"window.imagelistner.readImageUrl(objs[i].src);"
+" objs[i].onclick=function() " +
" { "
+" window.imagelistner.openImage(this.src); " +
" } " +
"}" +
"})()");
}
}
实现监听(内部类)
class JavaScriptInterface {
private Contextcontext;
private Listimages =new ArrayList<>();
public JavaScriptInterface(Context context) {
this.context = context;
}
@JavascriptInterface
public void readImageUrl(String img) {//把所有图片的url保存在ArrayList中
images.add(img);
}
//点击图片回调方法
//必须添加注解,否则无法响应
@JavascriptInterface
public void openImage(String img) {
Log.i("TAG","响应点击事件!");
int index =0;
ArrayList list = addImages();
for (String url : list)
if (url.equals(img)) index = list.indexOf(img);//获取点击图片在整个页面图片中的位置
Intent intent =new Intent();
Bundle bundle =new Bundle();
bundle.putStringArrayList("list_image", list);
bundle.putInt("index", index);
intent.putExtra("bundle", bundle);//将所有图片的url以及点击图片的位置作为参数传给启动的activity
intent.setClass(DetailActivity.this, ShowWebImageActivity.class);
startActivity(intent);//启动ViewPagerActivity,用于显示图片
}
//去重复
private ArrayList addImages() {
ArrayList list =new ArrayList<>();
Set set =new HashSet();
for (String cd :images) {
if (set.add(cd)) {
list.add(cd);
}
}
return list;
}
}
接下来展示ShowWebImageActivity中的代码,因为ShowWebImageActivity需要进行图片的滑动浏览,所以需
要用ViewPager,所以自定义了一个ViewPager,在里面处理了触摸事件,接下来就贴下代码:
public class ShowWebImageActivity extends AppCompatActivity {
private ArrayListimages;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showwebimage);
HackyViewPager hackyViewPager = (HackyViewPager) findViewById(R.id.view_pager);
Bundle bundle = getIntent().getBundleExtra("bundle");
images = bundle.getStringArrayList("list_image");
int index = bundle.getInt("index");
hackyViewPager.setAdapter(new ViewPagerAdapter());
hackyViewPager.setCurrentItem(index);
}
class ViewPagerAdapter extends PagerAdapter {
@Override
public int getCount() {
return images.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container,int position) {
View view = View.inflate(ShowWebImageActivity.this, R.layout.view_pager_item,null);
PhotoView photoView = (PhotoView) view.findViewById(R.id.photoview);
photoView.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
@Override
public void onPhotoTap(View view,float v,float v1) {
finish();
}
});
photoView.setBackgroundColor(Color.TRANSPARENT);
TextView indicator = (TextView) view.findViewById(R.id.indicator);
//用Glide加载图片
Glide.with(ShowWebImageActivity.this).load(images.get(position)).into(photoView);
CharSequence text = getString(R.string.viewpager_indicator, position +1,images.size());
//设置indicator
indicator.setText(text);
container.addView(view, ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.MATCH_PARENT);
return view;
}
@Override
public void destroyItem(ViewGroup container,int position, Object object) {
container.removeView((View) object);
}
}
}
自定义ViewPager:
public class HackyViewPager extends ViewPager {
private boolean isLocked;
public HackyViewPager(Context context) {
super(context);
isLocked =false;
}
public HackyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
isLocked =false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {//用于处理Touch事件
if (!isLocked) {
try {
return super.onInterceptTouchEvent(ev);
}catch (IllegalArgumentException e) {
e.printStackTrace();
return false;
}
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return !isLocked &&super.onTouchEvent(event);
}
}
相关布局文件:
MainActivity布局中只有一个简单的webView;
ViewPagerActivity布局中也只是一个HackViewPager;
HackViewPager中每一个View的布局:
view_pager_item.xml:
<?xmlversion="1.0"encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<uk.co.senab.photoview.PhotoView
android:id="@+id/photoview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="@+id/indicator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center"
android:textSize="18sp"
android:textColor="@android:color/black"
android:text="@string/viewpager_indicator"
android:background="@android:color/transparent"/>
</RelativeLayout>
用到了一个@string/viewpager_indicator为
<string name="viewpager_indicator">%1$d/%2$d</string>
以上是借用的这两篇文章
https://blog.csdn.net/smileiam/article/details/72123227
https://www.jb51.net/article/130645.htm