How to add padding around a WebView
Solution 1:
The WebView has a bug in the padding implementation. Setting a padding on a webview won't pad the actual web page, but WILL pad the scrollbars. It's only partially working as expected. Your solution is the best way to achieve 'padding' for a WebView.
Solution 2:
Another workaround for this problem could be in javascript usage. So when your webpage is loaded you can do such js call to set paddings:
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:document.body.style.margin=\"8%\"; void 0");
}
});
Solution 3:
Alternative approach would be to set the WebView inside of a ScrollView
Then you can add left/right margin to the WebView and it will get the padding effect. The scrolling however will be handled by the 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>
This will cause the scrollbar to be placed outside of the WebView which is the behavior I wanted for my app.
Solution 4:
Just try to add this CSS:
<body style='margin:X;padding:X;'>
Solution 5:
@Sergii's code didn't work for me, but following does
mWebView.setWebViewClient(new mWebViewClient(){
@Override
public void onPageFinished(WebView web, String url) {
web.loadUrl("javascript:(function(){ document.body.style.paddingTop = '55px'})();");
}
});
You can change paddingTop
to paddingBottom, paddingRight, paddingLeft
too. Change the 55px
value to whatever you desire. Additionally, enable JavaScript for your webview
webView.settings.javaScriptEnabled = true