user1777136
user1777136

Reputation: 1756

Android WebView full page div

I have a WebView in the Android app, wherein I want to render a full-height div. Obviously this is easy to do in Chrome or any other browser. This is the code that works fine in Chrome.

<!DOCTYPE html>
<html>
    <head>
        <style>
            html, body { height: 100%; }
            body > div { height: 100%; background: yellow; }
        </style>
    </head>
    <body>
        <div>I should be full height</div>
    </body>
</html>

In Chrome it looks like this:

Chrome

The exact same html rendered in the WebView looks like this: Android WebView

How can I make the div render at full height in the WebView? I have also tried the vh unit, flexbox, a viewport meta tag, but everything seems to fail because the body does not have a real height.

Upvotes: 0

Views: 1848

Answers (1)

BigDru
BigDru

Reputation: 161

MainActivity.java

package com.dru.experiment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;


public class MainActivity extends AppCompatActivity {

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

        WebView wv = (WebView) findViewById(R.id.webView);
        wv.setBackgroundColor(Color.rgb(40,40,40));
        wv.loadUrl("file:///android_asset/index.html");
    }
}

activity_main.xml (layout file)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webView"
        android:visibility="visible" />
</LinearLayout>

assets/index.html

<!DOCTYPE html>
<html>
    <head>
        <style>
            html, body { height: 100%; }
            body > div { height: 100%; background: yellow; }
        </style>
    </head>
    <body>
        <div>I should be full height</div>
    </body>
</html>

styles.xml

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>

My result:

Result

If the question was just about your html code, it works.

If it's about the webView, I am unsure as to why your resulting div was not yellow. Also maybe you forgot to match_parent for width and height in the layout (or java file for dynamically create views).

Upvotes: 2

Related Questions