Search This Blog

Support my cause by downloading

Tuesday, 2 December 2014

WebView Scroll Vertically : WebView scroll in one direction after zoom in android

Android WebView allow to load HTML content. Recently i was facing issue regarding zoom of WebView. What my requirement was, for scroll WebView content vertically regardless of its zoom level. Simply i want to stop horizontal scroll of webview.
I came across meta tag ViewPort and it did a lot of help with some attribute of WebSettings dynamically.

  • Wrap WebView inside ScrollView
  • Meta Tag viewport : Attach this meta tag immediately after <head>

<meta name="viewport" content="width=device-width,height=device-height,target-densityDpi=device-dpi,user-scalable=yes,initial-scale=0.5, maximum-scale=2, minimum-scale=0.5" />

If you don't have control on HTML content, then read HTML content in one string and then append above tag and then write to file again or use with webview's method loadwithBaseURL

StringBuilder mBuilder = new StringBuilder(mBuffer.toString().replace("<head>",
"<head><meta name=\"viewport\" content=\"width=device-width,height=device-height,target-densityDpi=device-dpi,user-scalable=yes,initial-scale=0.5, maximum-scale=2, minimum-scale=0.5\" />"));

mBuffer is the HTML string. you can change WebView's scale according to requirement

  • Attribute need to set dynamically are 

view.getSettings().setLoadWithOverviewMode(true);
view.getSettings().setUseWideViewPort(true);
view.setWebChromeClient(webChromeClient);
view.getSettings().setBuiltInZoomControls(true);
view.getSettings().setSupportZoom(true);

where view is reference of WebView.

Achieve Through this Article 

  •  Content will fit to new line to scroll WebView only vertically
  •  Fit content to initial scale using Meta Viewport
  • Content will not go more than WebView width




Android News and source code