如何将 WebView 的内容居中?

How can i center the content of a WebView?

我的应用程序的一部分从 URL 将图像加载到 WebView 中。 对 WebView 使用以下设置:

myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setDisplayZoomControls(false);
myWebView.getSettings().setLoadWithOverviewMode(true);
myWebView.getSettings().setUseWideViewPort(true);

布局中的相关部分XML:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent" >

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none" />

</RelativeLayout>

这个问题,如果图像的高度小于屏幕,它看起来与 WebView 的顶部对齐。

是否可以居中对齐?

我尝试了以下方法,但它始终不起作用,不知道为什么。

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent" >

    <WebView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:scrollbars="none" />

</RelativeLayout>

如有任何帮助,我们将不胜感激。

提前致谢。

编辑: 用 CSS 尝试了以下方法,仍然不起作用(图像显示,但不是垂直居中)。

myWebView.loadDataWithBaseURL(null, "<html><head><style>img {margin-top:auto;margin-bottom:auto}</style></head><body><img src=\"" + url + "\"></body></html>", "html/css", "utf-8", null);

编辑2: Bojan Kseneman 的解决方案有效。我正在使用

android:configChanges="orientation|keyboardHidden|screenSize

这就是为什么一开始它似乎是错误的。从我的 Manifest.xml 中删除了这一行修复了问题(在这种情况下处理 onSaveInstanceState 当然是必要的)。

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}