我在 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、视口(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>
我的结果:
如果问题只是关于您的 html 代码,那么它可以解决问题。
如果是关于 webView,我不确定为什么你的结果 div 不是黄色的。也可能您忘记了 match_parent 布局中的宽度和高度(或用于动态创建 View 的 java 文件)。
关于Android WebView整页div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33378117/