Android WebView: how to let the css use the entire

2019-02-27 18:32发布

问题:

I have a very responsive html/css page that uses position:absolute to put elements in place. e.g. a username input will have

position:absolute;
top:30%;
height:8%;
left:35%;
right:65%;

Everything works well in all browsers but webView android has a problem with the height.

It seems that it adapts itself to the height of the content instead of "being" of a certain height like any browser, and let the css deal with that arbitrary height.

I don't see any issue with the width but that might be an illusion.

I tried with and without height=device-height in the viewport meta tag. Does not change anything.

Here's my webView code:

public void openWebview(String url){
    WebView webView = (WebView) findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    webView.setWebViewClient(new ourViewClient());
    try {
        webView.loadUrl(url);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public class ourViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

回答1:

So in my case the problem was that I was setting the height of WebView using align parent instead of math_parent.

I was using this:

android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"

instead of this, THE RIGHT WAY:

android:layout_width="match_parent"
android:layout_height="match_parent"