Android WebView整页div

标签 android html css webview

我在 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 中它看起来像这样:

Chrome

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

如何使 div 在 WebView 中以全高呈现?我还尝试了 vh 单元、flexbox、视口(viewport)元标记,但一切似乎都失败了,因为 body 没有真正的高度。

最佳答案

主 Activity .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>

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>

样式.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>

我的结果:

Result

如果问题只是关于您的 html 代码,那么它可以解决问题。

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

关于Android WebView整页div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33378117/

相关文章:

jquery - 使 Jquery Capty 对来自 ajax 请求的数据产生影响

html - 水平显示嵌套 UL 的垂直导航菜单

javascript - 如何使用javascript根据另一个输入的值限制输入

c++ - 有没有办法修改样式表,以便将带有空标签的 XML 文档转换为 <tag/>?

html - 如何仅使用 CSS 将 Div 固定到页面顶部

Android MediaController 位置

java - setOnEditorActionListener() 方法不适用于输入类型 textMultiline 以及键盘中的输入按钮

android - 突出显示可点击跨度点击

javascript - 具有多级下拉菜单的最简单的 JQuery 动画导航栏

android - 在 Android 中单击带有传递参数的监听器方法