[android] Android Webview - Webpage should fit the device screen

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?

This question is related to android webview scaling android-webview

The answer is


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);

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.


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


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());

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!


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);

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);

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);

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);
    }
};

All you need to do is simply

webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);

int PIC_WIDTH= webView.getRight()-webView.getLeft();

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!


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


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.


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.


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.


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.


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.


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


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>

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to webview

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead? Android Webview gives net::ERR_CACHE_MISS message Swift Open Link in Safari How to load html string in a webview? how to display progress while loading a url to webview in android? Download file inside WebView How to pass html string to webview on android how to get html content from a webview? Android webview slow Android WebView not loading an HTTPS URL

Examples related to scaling

Can anyone explain me StandardScaler? How to scale images to screen size in Pygame How can I make an svg scale with its parent container? CSS scale down image to fit in containing div, without specifing original size Image scaling causes poor quality in firefox/internet explorer but not chrome How to scale down a range of numbers with a known min and max value Android and setting width and height programmatically in dp units Android Webview - Webpage should fit the device screen

Examples related to android-webview

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS Is `shouldOverrideUrlLoading` really deprecated? What can I use instead? Embed Youtube video inside an Android app Android WebView not loading URL Playing HTML5 video on fullscreen in android webview How to load html string in a webview? Android webview launches browser when calling loadurl Add custom headers to WebView resource requests - android Android WebView not loading an HTTPS URL How to load external webpage in WebView