Atma
Atma

Reputation: 29767

android webview goes more than full width for responsive sites

I have a simple webview:

<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />

Which is called like this:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView myWebView = (WebView) findViewById(R.id.webview);
        myWebView.loadUrl("http://example.com");
    }

The problem is that the site I am trying to render doesn't go into responsive mode. The width goes beyond the screen causing me to scroll.

I have tried widths including: fill_parent, match_parent, and wrap_content and none of them work.

What can I do to make the webpage render responsive, staying in the confines of the screen without scrolling horizontally?

Upvotes: 6

Views: 11730

Answers (3)

Youssef El-Amrani
Youssef El-Amrani

Reputation: 1

The error is displayed in the line

webView.setInitialScale((int) (getScale());

Upvotes: 0

Jon Alexandar
Jon Alexandar

Reputation: 151

I've found the most way to have the webview render properly by using setScale:

webView.setInitialScale((int) (getScale());

were getScale method caluclates the screen size using this alogrithm:

metrics.density*10

Then you can use a factor of the scale by dividing by a value less than 1.5 to fine tune it

Upvotes: 0

Mikhail Naganov
Mikhail Naganov

Reputation: 6861

You are missing a couple of setup calls that make WebView to render more like a mobile browser:

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

Optionally, you can also enable pinch-zooming:

myWebView.getSettings().setSupportZoom(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setDisplayZoomControls(false);

And as @Hylianpuffball correctly noted, your website should be ideally using <viewport> tag for controlling its presentation.

Upvotes: 17

Related Questions