80

I am trying to get the WebView to have similar behavior as the android browser. The browser opens all pages in a way that tries to fit their width to the screen. However, the default behavior of the WebView is to start at a 100% pixel scale so it starts zoomed in on the top left corner.

I have spent the last couple hours trying to find a way to get the WebView to scale the page to the screen like it does in the browser but I'm not having any luck. Has anyone found a way to accomplish this?

I see is a setting called setLoadWithOverviewMode, but that didn't appear to do anything at all. I also experimented with setInitialScale but on different screen sizes and web page sizes that won't be as graceful as the browsers scaling.

Any one have any leads?

Thanks

EDIT: Brian's method seems to work when the phone in landscape but not in portrait. In portrait it is close but still does not fit the whole screen in the page. I starting this bounty with the hope there is a sure-fire way to get the initial zoom to fit the page to the width of the page in any orientation or screen size.

Tushar Vengurlekar
  • 7,649
  • 8
  • 33
  • 48
cottonBallPaws
  • 21,220
  • 37
  • 123
  • 171
  • @Sam, yep the accepted solution below works for me. – cottonBallPaws Dec 13 '11 at 16:04
  • for some reason i spent a whole day around this and it worked only in api7 and not above. Finally had to implement the same using setInitialScale and calculating the initial scale manually. By the way i had a single image with 480x800 dimensions. – Samuel Dec 14 '11 at 00:59
  • Working for me on every device I have tried it on, from api level 7 up through 14. – cottonBallPaws Dec 15 '11 at 22:23

9 Answers9

164

The following code loads the desktop version of the Google homepage fully zoomed out to fit within the webview for me in Android 2.2 on an 854x480 pixel screen. When I reorient the device and it reloads in portrait or landscape, the page width fits entirely within the view each time.

BrowserLayout.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

     <WebView android:id="@+id/webview"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent" />
</LinearLayout>

Browser.java:

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class Browser extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.BrowserLayout);

        String loadUrl = "http://www.google.com/webhp?hl=en&output=html";

        // initialize the browser object
        WebView browser = (WebView) findViewById(R.id.webview);

        browser.getSettings().setLoadWithOverviewMode(true);
        browser.getSettings().setUseWideViewPort(true);

        try {
            // load the url
            browser.loadUrl(loadUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Brian
  • 16,196
  • 3
  • 27
  • 28
  • Thanks Brian, that appears to be working at first glance. I'm going to test a bunch more sites before I reward the bounty, but this looks promising! – cottonBallPaws Dec 01 '10 at 15:28
  • it doesn't work for me. It seems the the zoom is set after the page loads – jiduvah Apr 05 '12 at 09:04
  • This worked great... how do people come up with these solutions?? Trial and error, or do you have some sacred tome? – MetaGuru Oct 15 '12 at 17:24
  • 6
    This solution also did not work for me. I get a lot of black space to the right and bottom of the content. I'm loading an image from the assets folder instead of a web page, though. Could that be why? – SilithCrowe Dec 10 '12 at 19:49
  • Thanks so much , you answer helped me after hours of search :) – Muhannad A.Alhariri Dec 29 '12 at 23:06
  • @SilithCrowe - I see the same problem, using the above code works on 3 out of 4 android devices, but 1 device (HTC Desire X) the right-hand side of the page is blank space. Did you find a solution? – Mr. Bungle Jun 12 '13 at 17:10
  • Can you help me on this? https://stackoverflow.com/questions/49098464/loading-gif-in-webview-not-adjusting-to-webview – StuartDTO Mar 05 '18 at 19:36
  • Thanks. Also add `browser.setInitialScale(30);` as written below. – CoolMind Jul 24 '18 at 08:52
20

I figured out why the portrait view wasn't totally filling the viewport. At least in my case, it was because the scrollbar was always showing. In addition to the viewport code above, try adding this:

    browser.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    browser.setScrollbarFadingEnabled(false);

This causes the scrollbar to not take up layout space, and allows the webpage to fill the viewport.

Hope this helps

grimmdp
  • 271
  • 3
  • 4
12

It is and old question but let me add a detail just in case more people like me arrive here.

The excellent answer posted by Brian is not working for me in Jelly Bean. I have to add also:

browser.setInitialScale(30);

The parameter can be any percentage tha accomplishes that the resized content is smaller than the webview width. Then setUseWideViewPort(true) extends the content width to the maximum of the webview width.

Ivan BASART
  • 819
  • 2
  • 11
  • 15
  • My webpage displayed in webview consists of lot of Javascript, it is more like OSD in TV, widgets with buttons. I used your solution and I have 2 comments on that: 1. first load of webview is unsuccessfull, webview is black 2. 2nd one is correct, but I can double-tap and that is something I don't want, because it scales the widgets and buttons stop working then. Any help you could provide? Thanks. – MartinC Oct 25 '13 at 12:12
  • It should be noted, that the default value of `WebView.setInitialScale(int)` is 0 not 100. [Link to Documentation](https://developer.android.com/reference/android/webkit/WebView.html#setInitialScale(int)) – DBX12 Sep 26 '16 at 10:46
  • Thanks, it helped. I tried 5, 10, 30 and 70 percents. In case of 70 it resized a large page to 70%, so, scrollbars appeared. In case of 5-30% it resized the page normally. – CoolMind Jul 24 '18 at 08:57
7

Try using a wide viewport:

 webview.getSettings().setUseWideViewPort(true);
Brian
  • 16,196
  • 3
  • 27
  • 28
  • 1
    Thank you, that seems to be in the right direction. That in and of itself didn't seem to do anything, but with the combination of setInitialScale(50) it worked perfectly in portrait. However, holding the phone in landscape, it doesn't fit to screen. Are there other settings I should be using in addition to that one? Here is what I have currently: setBuiltInZoomControls(true), setUseWideViewPort(true), setInitialScale(50). I would like it to fit well to the screen no matter the size or density of the screen. Thanks again. – cottonBallPaws Sep 28 '10 at 19:30
3

//for images and swf videos use width as "100%" and height as "98%"

mWebView2.getSettings().setJavaScriptEnabled(true);
mWebView2.getSettings().setLoadWithOverviewMode(true);
mWebView2.getSettings().setUseWideViewPort(true);
mWebView2.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
mWebView2.setScrollbarFadingEnabled(true);
Ashish Anand
  • 3,531
  • 6
  • 34
  • 45
  • can you help me on this https://stackoverflow.com/questions/49098464/loading-gif-in-webview-not-adjusting-to-webview – StuartDTO Mar 05 '18 at 19:34
1

I'm working with loading images for this answer and I want them to be scaled to the device's width. I find that, for older phones with versions less than API 19 (KitKat), the behavior for Brian's answer isn't quite as I like it. It puts a lot of whitespace around some images on older phones, but works on my newer one. Here is my alternative, with help from this answer: Can Android's WebView automatically resize huge images? The layout algorithm SINGLE_COLUMN is deprecated, but it works and I feel like it is appropriate for working with older webviews.

WebSettings settings = webView.getSettings();

// Image set to width of device. (Must be done differently for API < 19 (kitkat))
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
    if (!settings.getLayoutAlgorithm().equals(WebSettings.LayoutAlgorithm.SINGLE_COLUMN))
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
} else {
    if (!settings.getLoadWithOverviewMode()) settings.setLoadWithOverviewMode(true);
    if (!settings.getUseWideViewPort()) settings.setUseWideViewPort(true);
}
Community
  • 1
  • 1
Daniel Handojo
  • 612
  • 5
  • 19
0

If you have the web view figured out but your images are still out of scale, the best solution I found (here) was simply prepending the document with:

<style>img{display: inline; height: auto; max-width: 100%;}</style>

As a result all images are scaled to match the web view width.

dsalaj
  • 2,857
  • 4
  • 34
  • 43
0

in Kotlin You can use,

webView.isScrollbarFadingEnabled = true
webView.setInitialScale(100)
Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256
0

You can achieve that easily with Mozilla's GeckoView Library. You can use it instead of WebView. But big disadvantage of this method is this library is about 50 MB size.

Samir Alakbarov
  • 1,120
  • 11
  • 21