问题
I need to add margins to a webview programmatically. I would like to do something like below:
public void setSideMargin(final int sideMargin, int id) {
WebView webView = (WebView) ((Activity) context)
.findViewById(id);
WebView.LayoutParams p = new WebView.LayoutParams(
WebView.LayoutParams.MATCH_PARENT,
WebView.LayoutParams.WRAP_CONTENT);
p.leftMargin = sideMargin;
p.rightMargin = sideMargin;
webView.setLayoutParams(p);
}
This is obviously wrong I know but is there anything like this that I can do to add the margins programmatically? Thanks
回答1:
The thing to understand with LayoutParams
is this: The LayoutParams
does not depend on the element it is set to, but on the parent.
It is an indication given to the parent regarding the positioning of the element.
Therefore, if your WebView
is in a LinearLayout
, getLayoutParams
will get you a LinearLayout.LayoutParams
.
Which means that, in order to have a descendant of MarginLayoutParam
, a LayoutParams that supports margins, your WebView must be placed in a ViewGroup
that supports margins, such as LinearLayout
or RelativeLayout
. (see the list of descendants http://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html ). In other words, WebView
itself does not support margins, its parent does.
In which case, you should cast the LayoutParams
from the WebView
to:
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) webView.getLayoutParams();
Once you have that, you can modify the margins :
p.leftMargin = sideMargin;
p.rightMargin = sideMargin;
webView.setLayoutParams(p);
回答2:
Try with this code:
WebView.LayoutParams layoutParams = (WebView.LayoutParams) webView.getLayoutParams();
webView.layoutParams.leftMargin = sideMargin;
webView.layoutParams.rightMargin = sideMargin;
webView.setLayoutParams(layoutParams);
If doesn't work , then take linearlayout parent of this view and insert padding for it.
Example code:
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) webView.getParent().getLayoutParams();
layoutParams.setMargins(sideMargin, 0, sideMargin, 0);
((LinearLayout)webView.getParent()).setLayoutParams(layoutParams);
2th Example code:
LinearLayout webviewLayout = (LinearLayout) webView.getParent();
webviewLayout.setPadding(sideMargin,0,sideMargin,0);
来源:https://stackoverflow.com/questions/23519946/android-add-margins-programmatically-to-webview