如何使WebView的内容居中?

时间:2022-11-25 00:00:42

A part of my app loads an image into a WebView from a URL. Using the following settings for the WebView:

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

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

Relevant part from the layout XML:

布局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>

The problem with this, if the image if smaller in height than the screen, it appears aligned to the top of the WebView.

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

Is it possible to align it to the center?

是否可以将其与中心对齐?

I tried the following, but it just doesn't work all the time, no idea why.

我尝试了下面这个,但它一直不起作用,不知道为什么。

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

Any help would be appreciated.

任何帮助,将不胜感激。

Thanks in advance.

提前致谢。

edit: Tried the following with CSS, still doesn't work (the image is displayed, but not centered vertically).

编辑:使用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);

edit2: Bojan Kseneman's solution is working. I was using

edit2:Bojan Kseneman的解决方案正在发挥作用。我在用

android:configChanges="orientation|keyboardHidden|screenSize

that's why it seemed to be wrong at first. Removed this line from my Manifest.xml fixed the problems (handling onSaveInstanceState is of course necessary in this case).

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

1 个解决方案

#1


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

#1


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