【问题标题】:How can i center the content of a WebView?如何使 WebView 的内容居中?
【发布时间】:2015-05-09 16:33:45
【问题描述】:

我的应用程序的一部分将图像从 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 当然是必要的)。

【问题讨论】:

  • 您可以使用 CSS 在 webview 中垂直和水平居中图像。

标签: java android html css webview


【解决方案1】:
.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

【讨论】:

  • 感谢您的回答,试过了,但似乎不起作用。代码在我的原始帖子中。 (使用 margin-top 和 margin-bottom,因为我想垂直居中,而不是水平居中)
  • 查看我的编辑。我虽然你需要它水平对齐。
  • 谢谢,试过了,似乎可以工作,但只能在纵向模式下,并且只能在方向改变之后。所以它最初仍然在顶部对齐,我切换到横向,回到纵向并且它正确居中。
猜你喜欢
  • 2012-05-18
  • 1970-01-01
  • 2013-08-03
  • 1970-01-01
  • 2020-12-29
  • 2021-06-18
  • 2015-06-13
  • 2012-02-17
  • 2013-06-17
相关资源
最近更新 更多