如何在WebView周围添加填充

Dan*_*n J 38 android padding android-layout android-webview

我的布局文件定义了一个WebView,下面有一些固定的高度按钮.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:fadingEdge="none">

  <WebView
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="1.0"/>

  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="60dp"
    android:padding="8dp">

    <Button
      android:text="Decline"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_weight="1.0">
    </Button>

    <Button
      android:text="Accept"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_weight="1.0">
    </Button>

  </LinearLayout>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

我正在尝试在WebView周围添加填充,就像文本一直运行到UI的边缘一样.

我尝试添加android:padding="8dp"到WebView,但没有添加填充.我也尝试过paddingLeft和paddingRight,但它们也没有用.

网页视图 API文档确认它查看,支持继承的android:填充属性,所以我很惊讶这没有奏效.

有人知道这是一个已知的问题,还是我的布局XML的一些互动,我不理解?

仅供参考,我的解决方法是在WebView周围添加额外的LinearLayout,并将填充添加到其中:

  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="1.0"
    android:padding="8dp">

    <WebView
      android:id="@+id/webview"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"/>

  </LinearLayout>
Run Code Online (Sandbox Code Playgroud)

zrg*_*giu 40

WebView在填充实现中存在错误.在webview上设置填充不会填充实际的网页,但会填充滚动条.它只是按预期部分工作.您的解决方案是实现WebView"填充"的最佳方式.

  • 10周年纪念日,耶! (8认同)
  • 6年仍然是一个错误 (4认同)
  • 12年了还是个bug (4认同)
  • 4天后9年仍然是一个bug (3认同)
  • 7 年仍然是一个错误 (2认同)

Ser*_*gii 25

此问题的另一个解决方法可能是javascript使用.因此,当您的网页加载时,您可以执行此类js调用以设置填充:

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        webView.loadUrl("javascript:document.body.style.margin=\"8%\"; void 0");
    }
});
Run Code Online (Sandbox Code Playgroud)


Vos*_*ski 6

另一种方法是将WebView设置在ScrollView内

然后,您可以向WebView添加左/右页边距,它将获得填充效果。但是,滚动将由ScrollView处理。

<ScrollView style="@style/MatchMatch">

    <WebView
        android:id="@+id/my_web_view"
        android:layout_marginLeft="@dimen/webViewMargin"
        android:layout_marginRight="@dimen/webViewMargin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</ScrollView>
Run Code Online (Sandbox Code Playgroud)

这将导致滚动条放置在WebView之外,这是我想要为我的应用程序执行的行为。


mol*_*008 5

只需尝试添加此 CSS:

<body style='margin:X;padding:X;'>
Run Code Online (Sandbox Code Playgroud)

  • 我认为这个答案与问题无关。虽然我知道它可能真的有效,但问题是关于 Android 布局问题,而不是关于“WebView”中显示的 html 内容。 (2认同)