【问题标题】:Android WebView full page divAndroid WebView 整页 div
【发布时间】:2015-10-27 20:44:20
【问题描述】:

我在 Android 应用中有一个 WebView,我想在其中呈现一个全高 div。显然,这在 Chrome 或任何其他浏览器中很容易做到。这是在 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>

在 Chrome 中看起来像这样:

在 WebView 中呈现的完全相同的 html 如下所示:

如何让 div 在 WebView 中以全高呈现?我也尝试过vh 单元、flexbox、视口元标记,但一切似乎都失败了,因为身体没有真正的高度。

【问题讨论】:

    标签: android html css webview


    【解决方案1】:

    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(布局文件)

    <?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>
    

    资产/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>
    

    我的结果:

    如果问题只是关于您的 html 代码,它可以工作。

    如果是关于 webView,我不确定为什么生成的 div 不是黄色的。也可能你忘了 match_parent 在布局中的宽度和高度(或用于动态创建视图的 java 文件)。

    【讨论】:

    • 谢谢,match_parent 确实是我所缺少的。
    • 嗨,对不起,但不正确,您的更改背景静态“ wv.setBackgroundColor(Color.rgb(40,40,40));”不是从 url 获取 :) 好尝试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多