131

I have tried the following to fit the webpage based on the device screen size.

mWebview.setInitialScale(30);

and then set the metadata viewport

<meta name="viewport" content="width=320, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=0;"/>
<meta name="viewport" content="width=device-width, target-densityDpi=medium-dpi"/>

But nothing works, webpage is not fixed to the device screen size.

Can anyone tell me how to get this?

Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
SWDeveloper
  • 1,749
  • 5
  • 18
  • 20

22 Answers22

327

You can use this

    WebView browser = (WebView) findViewById(R.id.webview);
    browser.getSettings().setLoadWithOverviewMode(true);
    browser.getSettings().setUseWideViewPort(true);

this fixes size based on screen size.

Tushar Vengurlekar
  • 7,649
  • 8
  • 33
  • 48
  • 4
    This feet the screen but does not allow you to make zoom in/out anymore. Could this issue bee improved?, I know it is possible on IOS. – AlexAndro Mar 20 '12 at 11:27
  • http://stackoverflow.com/questions/21620732/html-data-not-display-correct-in-webview-gettinng-from-json-webservice-in-androi/21620839?noredirect=1#comment32670624_21620839 can you help me ? – Mahesh Feb 07 '14 at 07:31
  • 2
    this settings work for me but only for the width, in same cases now it is cuting off the height – albanx Oct 29 '15 at 17:33
  • 1
    This is the best solution to achieve this I've found so far. – fragon Nov 24 '15 at 12:18
  • 1
    The fact that the solution is built in really wins me over. – Daniel Handojo Jan 29 '16 at 07:34
  • 6
    To add zoom, add the following: webview.getSettings().setBuiltInZoomControls(true); webview.getSettings().setDisplayZoomControls(false); – Andrew Oct 17 '17 at 08:56
  • @albanx what you did for height? any solution? – Arnold Brown May 18 '19 at 09:56
93

You have to calculate the scale that you need to use manually, rather than setting to 30.

private int getScale(){
    Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
    int width = display.getWidth(); 
    Double val = new Double(width)/new Double(PIC_WIDTH);
    val = val * 100d;
    return val.intValue();
}

Then use

WebView web = new WebView(this);
web.setPadding(0, 0, 0, 0);
web.setInitialScale(getScale());
danh32
  • 6,234
  • 2
  • 38
  • 39
  • 7
    Thanks for your reply, u r right, it works. but I have different issue. I am not loading an image, loading the webpage in the webview, So how to find out the webpage width (PIC_WIDTH). – SWDeveloper Oct 13 '10 at 15:21
  • 1
    Ah, I missed that constant in there. Sorry about that. I am not sure how you can get the width of the actual webpage. – danh32 Oct 13 '10 at 18:59
  • 4
    PIC_WIDTH was a constant that I knew beforehand, since I was just displaying a single image from the assets folder. As I said above, I don't know how you can get the width of the actual webpage. – danh32 Feb 08 '12 at 14:43
  • but how about height? Do Android tablets have same ratio? – MartinC Oct 22 '13 at 11:38
  • http://stackoverflow.com/questions/21620732/html-data-not-display-correct-in-webview-gettinng-from-json-webservice-in-androi/21620839?noredirect=1#comment32670624_21620839 can you help me / – Mahesh Feb 07 '14 at 07:31
  • This solution definitely best solution. Before that I use javascript code for changing view metaport tag. This tag are used after page loading and this presents some lags, however I solved my delay problem. – burakim Jun 12 '15 at 14:38
  • what would be the expected value of PIC_WIDTH – Maheshwar Ligade Jun 23 '16 at 01:38
  • 1
    @MaheshwarLigade i use PIC_WIDTH = 360 – Nicholas Ng Jul 29 '16 at 10:54
  • 1
    @danh32 tell the value of PIC_WIDTH ... as 360 is not fine for me. – Maveňツ Jan 04 '17 at 11:19
  • @danh32 Can the scale density (hdpi, mdpi) has impact on the calculation for scale? – Abhinav Saxena Aug 04 '17 at 06:03
45

These settings worked for me:

wv.setInitialScale(1);
wv.getSettings().setLoadWithOverviewMode(true);
wv.getSettings().setUseWideViewPort(true);
wv.getSettings().setJavaScriptEnabled(true);

setInitialScale(1) was missing in my attempts.

Although documentation says that 0 will zoom all the way out if setUseWideViewPort is set to true but 0 did not work for me and I had to set 1.

Shabbir Dhangot
  • 8,954
  • 10
  • 58
  • 80
Doc
  • 1,094
  • 10
  • 18
  • 1
    I wasnt setting the intial scale, and it worked for me for years. ( i was just setting overview mode, and viewport). But a new device Ive just come across seemed to start zoomed in until the page refreshed. Setting intial scale fixed this for me. – IAmGroot Oct 18 '19 at 09:05
  • Didnt work for me as these settings were already used in my code, then it means there is issue with webpage content. Thanks! – sud007 Apr 19 '22 at 14:37
40

Friends,

I found a lot of import and great informations from you. But, the only way works for me was this way:

webView = (WebView) findViewById(R.id.noticiasWebView);
webView.setInitialScale(1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.loadUrl("http://www.resource.com.br/");

I am working on Android 2.1 because of the kind of devices from the company. But I fixed my problem using the part of informations from each one.

Thanks you!

Pranav
  • 52
  • 7
Josmar Peixe
  • 691
  • 7
  • 4
  • Then zooming doesn't work anymore. I'm the only one with this problem? – testing Mar 10 '16 at 09:42
  • @testing did you get any solution of it ? – Anshul Tyagi Jun 10 '16 at 08:14
  • @AnshulTyagi: No, I didn't. Because it was a test project for me I didn't further investigate into this. Let me know if you find something! – testing Jun 10 '16 at 08:24
  • @AnshulTyagi: For web pages [this approach](http://stackoverflow.com/a/6182669/426227) is working for me. For images I have to use something different ... – testing Sep 28 '16 at 09:48
  • Please change it to the latest code for Kotlin: `val displayMetrics = DisplayMetrics() windowManager.defaultDisplay.getMetrics(displayMetrics) var width = displayMetrics.widthPixels var height = displayMetrics.heightPixels` – Abhinav Saxena Oct 01 '21 at 11:08
  • getRealMetrics is also deprecated in OS level 31. See https://developer.android.com/reference/android/view/Display – Abhinav Saxena Oct 01 '21 at 11:45
25

Try with this HTML5 tips

http://www.html5rocks.com/en/mobile/mobifying.html

And with this if your Android Version is 2.1 or greater

  WebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
Peter O.
  • 32,158
  • 14
  • 82
  • 96
josebetomex
  • 419
  • 4
  • 9
15

All you need to do is simply

webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
Muhammad Aamir Ali
  • 20,419
  • 10
  • 66
  • 57
14

These work for me and fit the WebView to screen width:

// get from xml, with all size set "fill_parent"  
webView = (WebView) findViewById(R.id.webview_in_layout);  
// fit the width of screen
webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); 
// remove a weird white line on the right size
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);  

Thanks above advises and White line in eclipse Web view

Community
  • 1
  • 1
Nezneika
  • 146
  • 1
  • 7
13

I have same problem when I use this code

webview.setWebViewClient(new WebViewClient() {
}

so may be you should remove it in your code
And remember to add 3 modes below for your webview

    webview.getSettings().setJavaScriptEnabled(true);  
    webview.getSettings().setLoadWithOverviewMode(true);
    webview.getSettings().setUseWideViewPort(true);

this fixes size based on screen size

Linh
  • 433
  • 6
  • 11
8

I had video in html string, and width of web view was larger that screen width and this is working for me.

Add these lines to HTML string.

<head>
<meta name="viewport" content="width=device-width">
</head>

Result after adding above code to HTML string:

<!DOCTYPE html>
<html>

<head>
<meta name="viewport" content="width=device-width">
</head>


</html>
7
WebView browser = (WebView) findViewById(R.id.webview);
browser.getSettings().setLoadWithOverviewMode(true);
browser.getSettings().setUseWideViewPort(true);
browser.getSettings().setMinimumFontSize(40);

This works great for me since the text size has been set to really small by .setLoadWithOverViewMode and .setUseWideViewPort.

Steve
  • 71
  • 1
  • 2
6

You have to use HTML in your webView in this case. I solved this using following code

webView.loadDataWithBaseURL(null,
                "<!DOCTYPE html><html><body style = \"text-align:center\"><img src= "
                        + \"http://www.koenvangorp.be/photos/2005_09_16-moon_2000.jpg\"
                        + " alt=\"pageNo\" width=\"100%\"></body></html>",
                "text/html", "UTF-8", null);
Qadir Hussain
  • 8,721
  • 13
  • 89
  • 124
  • i guess is better to use px ot vh instead of %. % in iframes have some bugs on orientation changes – Siarhei Oct 25 '17 at 20:02
5

Making Changes to the answer by danh32 since the display.getWidth(); is now deprecated.

private int getScale(){
    Point p = new Point();
    Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
    display.getSize(p);
    int width = p.x; 
    Double val = new Double(width)/new Double(PIC_WIDTH);
    val = val * 100d;
    return val.intValue();
}

Then use

WebView web = new WebView(this);
web.setPadding(0, 0, 0, 0);
web.setInitialScale(getScale());
Ducktales
  • 312
  • 4
  • 11
  • I calculated that the scale should be < 1 or 100% so I compared my width with the PIC_WIDTH to get the ratio. More than that I also deducted some padding. – Abhinav Saxena Jun 26 '17 at 12:27
5

This seems like an XML problem. Open the XML document containing your Web-View. Delete the padding code at the top.

Then in the layout , add

android:layout_width="fill_parent"
android:layout_height="fill_parent"

In the Web-View, add

android:layout_width="fill_parent"
android:layout_height="fill_parent" 

This makes the Web-View fit the device screen.

Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
ZakiHacky
  • 59
  • 1
  • 3
3
webview.setInitialScale(1);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setJavaScriptEnabled(true);

will work, but remember to remove something like:

<meta name="viewport" content="user-scalable=no"/>

if existed in the html file or change user-scalable=yes, otherwise it won't.

Hoang Nguyen Huu
  • 1,202
  • 17
  • 17
3
int PIC_WIDTH= webView.getRight()-webView.getLeft();
Peter Olson
  • 139,199
  • 49
  • 202
  • 242
john
  • 49
  • 1
3

For any developer landed here and facing a problem dealing with Webview initial zoom/scale(especially in custom webpages).

   webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setUseWideViewPort(false); //make sure this method is false so setInitialScale() can work correctly
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.setInitialScale(110);
Mohamed Ben Romdhane
  • 1,005
  • 3
  • 11
  • 22
2

The getWidth method of the Display object is deprecated. Override onSizeChanged to get the size of the WebView when it becomes available.

WebView webView = new WebView(context) {

    @Override
    protected void onSizeChanged(int w, int h, int ow, int oh) {

        // if width is zero, this method will be called again
        if (w != 0) {

            Double scale = Double.valueOf(w) / Double.valueOf(WEB_PAGE_WIDTH);

            scale *= 100d;

            setInitialScale(scale.intValue());
        }

        super.onSizeChanged(w, h, ow, oh);
    }
};
SharkAlley
  • 11,399
  • 5
  • 51
  • 42
2

This will help in adjusting the emulator according to the webpage:

WebView wb;
//CALL THIS METHOD
wb.setInitialScale(50);

You can set the intial scale in percentage as shown above.

Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
jagadeesh
  • 49
  • 5
1

In theory the combination of:

settings.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS); 

with

settings.setUseWideViewPort(false)

fixes the problem, wrapping the content and fitting to the screen. But the NARROW_COLUMNS has been deprecated. I advice you to read this thread below that explores the issue in detail: https://code.google.com/p/android/issues/detail?id=62378

Alécio Carvalho
  • 13,481
  • 5
  • 68
  • 74
1

here's an updated version, not using deprecated methods, based upon @danh32's answer:

protected int getScale(Double contentWidth) {
    if(this.getActivity() != null) {
        DisplayMetrics displaymetrics = new DisplayMetrics();
        this.getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        Double val = displaymetrics.widthPixels / contentWidth * 100d;
        return val.intValue();
    } else {
        return 100;
    }
}

to be used alike:

int initialScale = this.getScale(420d);
this.mWebView.setInitialScale(initialScale);
Martin Zeitler
  • 1
  • 19
  • 155
  • 216
1

For reference, this is a Kotlin implementation of @danh32's solution:

private fun getWebviewScale (contentWidth : Int) : Int {
    val dm = DisplayMetrics()
    windowManager.defaultDisplay.getRealMetrics(dm)
    val pixWidth = dm.widthPixels;
    return (pixWidth.toFloat()/contentWidth.toFloat() * 100F)
             .toInt()
}

In my case, width was determined by three images to be 300 pix so:

webview.setInitialScale(getWebviewScale(300))

It took me hours to find this post. Thanks!

steven smith
  • 1,519
  • 15
  • 31
-5
WebView webView = (WebView)findViewById(R.id.web_view);
webView.setInitialScale((int) getResources().getDimension(R.dimen._50sdp)); // getActivity(). if you are at Fragment
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.loadDataWithBaseURL(null,here comes html content,"text/html","UTF-8", null);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setDisplayZoomControls(true);
webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
SmokeDetector
  • 751
  • 2
  • 8
  • 12