Android: banners in a pass-through overlay above the WebView

- createBanner / loadBanner / showBanner / hideBanner / setBannerLayout / destroyBanner, several banners keyed by
  bannerId, presets, ADAPTIVE (width in dp = CSS px) and CUSTOM sizes, placement name and bid floor.
- OverlayHost: a non-clickable FrameLayout next to the WebView; touches outside ad views fall through. Positions
  are measured from the WebView's on-screen rect and the window insets (system bars + display cutout), so they are
  right with Capacitor 7 margins, Capacitor 8 SystemBars padding or CSS-only insets.
- Adaptive banners without a fixed width are recreated and reloaded when the safe-area width changes (rotation).
- hide pauses auto refresh, show resumes it; all banner events with bannerId, adUnitId, adInfo and frame.
- Banners get the per-ad impression data listener; everything is destroyed in handleOnDestroy.
This commit is contained in:
CRTkafa 2026-10-10 03:35:25 +08:00
parent 479c4aadda
commit 4cf95e286d
3 changed files with 695 additions and 0 deletions

View file

@ -0,0 +1,405 @@
package fyi.crt.capacitor.levelplay;
import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.getcapacitor.JSObject;
import com.unity3d.mediation.LevelPlayAdError;
import com.unity3d.mediation.LevelPlayAdInfo;
import com.unity3d.mediation.LevelPlayAdSize;
import com.unity3d.mediation.banner.LevelPlayBannerAdView;
import com.unity3d.mediation.banner.LevelPlayBannerAdViewListener;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Banners (design §3, §6): LevelPlayBannerAdView instances keyed by bannerId, laid out in the OverlayHost.
* Main thread only; SDK callbacks are re-posted to the main thread.
*/
final class BannerManager {
interface Host {
@Nullable
Activity activity();
/** The overlay, attached on first use; null when the WebView has no parent. */
@Nullable
OverlayHost overlay();
boolean initialized();
void emit(String event, JSObject data);
com.unity3d.mediation.impression.LevelPlayImpressionDataListener impressionListener();
}
/** Owner decision Q4: adaptive banners follow safe-area width changes after the layout settled. */
private static final long ADAPTIVE_RECREATE_DELAY_MS = 250;
private final Host host;
private final Handler main = new Handler(Looper.getMainLooper());
private final Map<String, Slot> slots = new LinkedHashMap<>();
private final Runnable adaptiveCheck = this::recreateChangedAdaptive;
BannerManager(Host host) {
this.host = host;
}
private static final class Slot {
final String bannerId;
final String adUnitId;
final String size;
@Nullable
final Integer fixedAdaptiveWidth;
final int customWidth;
final int customHeight;
@Nullable
final String placementName;
@Nullable
final Double bidFloor;
String position = "bottom";
double offsetX;
double offsetY;
boolean respectSafeArea = true;
LevelPlayBannerAdView view;
LevelPlayAdSize adSize;
/** CSS px width the adaptive size was computed for. */
int adaptiveWidthUsed;
boolean visible;
boolean loadRequested;
double[] frame = OverlayMath.rect(0, 0, 0, 0);
Slot(
String bannerId,
String adUnitId,
String size,
@Nullable Integer fixedAdaptiveWidth,
int customWidth,
int customHeight,
@Nullable String placementName,
@Nullable Double bidFloor
) {
this.bannerId = bannerId;
this.adUnitId = adUnitId;
this.size = size;
this.fixedAdaptiveWidth = fixedAdaptiveWidth;
this.customWidth = customWidth;
this.customHeight = customHeight;
this.placementName = placementName;
this.bidFloor = bidFloor;
}
}
// ---------------------------------------------------------------------------------------------- API
JSObject create(JSObject o) throws CallError {
String adUnitId = o.getString("adUnitId");
if (adUnitId == null || adUnitId.isEmpty()) throw CallError.invalid("adUnitId is required");
String bannerId = nonEmpty(o.getString("bannerId"), adUnitId);
JSObject custom = o.getJSObject("customSize");
String size = o.getString("size");
if (size == null) size = custom != null ? "CUSTOM" : "ADAPTIVE";
if (!OverlayMath.isBannerSize(size)) throw CallError.invalid("Unknown banner size '" + size + "'");
int cw = 0, ch = 0;
if ("CUSTOM".equals(size)) {
if (custom == null) throw CallError.invalid("size CUSTOM needs customSize { width, height }");
cw = positiveInt(custom, "customSize.width", "width");
ch = positiveInt(custom, "customSize.height", "height");
}
Integer fixedWidth = null;
if (o.has("adaptiveWidth") && !o.isNull("adaptiveWidth")) {
fixedWidth = positiveInt(o, "adaptiveWidth", "adaptiveWidth");
}
Double bidFloor = null;
if (o.has("bidFloor") && !o.isNull("bidFloor")) {
Object v = o.opt("bidFloor");
if (!(v instanceof Number) || ((Number) v).doubleValue() < 0) throw CallError.invalid("bidFloor must be a number >= 0");
bidFloor = ((Number) v).doubleValue();
}
String placement = o.getString("placementName");
if (placement != null && placement.isEmpty()) placement = null;
Slot s = new Slot(bannerId, adUnitId, size, fixedWidth, cw, ch, placement, bidFloor);
applyLayout(s, o);
if (!host.initialized()) throw new CallError("NOT_INITIALIZED", "Call initialize() and wait for it before createBanner()");
if (slots.containsKey(bannerId)) throw new CallError("ALREADY_EXISTS", "Banner '" + bannerId + "' already exists; destroy it first");
Activity activity = host.activity();
if (activity == null) throw new CallError("NO_ACTIVITY", "No activity to attach the banner to");
OverlayHost overlay = host.overlay();
if (overlay == null) throw new CallError("NO_ACTIVITY", "The WebView is not attached to a view hierarchy");
buildView(s, activity, overlay);
slots.put(bannerId, s);
relayout(s, overlay);
return result(s);
}
void load(String bannerId) throws CallError {
Slot s = require(bannerId);
s.loadRequested = true;
s.view.loadAd();
}
JSObject show(String bannerId) throws CallError {
Slot s = require(bannerId);
OverlayHost overlay = host.overlay();
s.visible = true;
s.view.setVisibility(View.VISIBLE);
s.view.bringToFront();
s.view.resumeAutoRefresh();
if (overlay != null) relayout(s, overlay);
return result(s);
}
void hide(String bannerId) {
Slot s = slots.get(bannerId);
if (s == null) return;
s.visible = false;
s.view.setVisibility(View.GONE);
s.view.pauseAutoRefresh();
}
JSObject setLayout(JSObject o) throws CallError {
Slot s = require(o.getString("bannerId"));
applyLayout(s, o);
OverlayHost overlay = host.overlay();
if (overlay != null) relayout(s, overlay);
return result(s);
}
void destroy(String bannerId) {
Slot s = slots.remove(bannerId);
if (s != null) destroyView(s);
}
void destroyAll() {
main.removeCallbacks(adaptiveCheck);
for (Slot s : new ArrayList<>(slots.values())) destroyView(s);
slots.clear();
}
boolean isEmpty() {
return slots.isEmpty();
}
/** Overlay layout pass: re-place every banner and schedule the adaptive width check (Q4). */
void onLayoutChanged(OverlayHost overlay) {
boolean adaptiveChanged = false;
for (Slot s : slots.values()) {
relayout(s, overlay);
if (followsWidth(s) && currentAdaptiveWidth(s, overlay) != s.adaptiveWidthUsed) adaptiveChanged = true;
}
main.removeCallbacks(adaptiveCheck);
if (adaptiveChanged) main.postDelayed(adaptiveCheck, ADAPTIVE_RECREATE_DELAY_MS);
}
// ---------------------------------------------------------------------------------------------- internals
private Slot require(@Nullable String bannerId) throws CallError {
if (bannerId == null || bannerId.isEmpty()) throw CallError.invalid("bannerId is required");
Slot s = slots.get(bannerId);
if (s == null) throw CallError.notFound("Banner", bannerId);
return s;
}
private static void applyLayout(Slot s, JSObject o) throws CallError {
if (o.has("position") && !o.isNull("position")) {
String p = o.getString("position");
if (!OverlayMath.isPosition(p)) throw CallError.invalid("position must be 'top', 'bottom' or 'center'");
s.position = p;
}
if (o.has("offsetX") && !o.isNull("offsetX")) s.offsetX = finite(o, "offsetX");
if (o.has("offsetY") && !o.isNull("offsetY")) s.offsetY = finite(o, "offsetY");
if (o.has("respectSafeArea") && !o.isNull("respectSafeArea")) {
Object v = o.opt("respectSafeArea");
if (!(v instanceof Boolean)) throw CallError.invalid("respectSafeArea must be a boolean");
s.respectSafeArea = (Boolean) v;
}
}
private static double finite(JSObject o, String key) throws CallError {
Object v = o.opt(key);
if (!(v instanceof Number)) throw CallError.invalid(key + " must be a number");
double d = ((Number) v).doubleValue();
if (Double.isNaN(d) || Double.isInfinite(d)) throw CallError.invalid(key + " must be finite");
return d;
}
private static int positiveInt(JSObject o, String label, String key) throws CallError {
Object v = o.opt(key);
if (!(v instanceof Number)) throw CallError.invalid(label + " must be a positive number");
double d = ((Number) v).doubleValue();
if (!(d >= 1) || Double.isInfinite(d)) throw CallError.invalid(label + " must be a positive number");
return (int) Math.round(d);
}
private static String nonEmpty(@Nullable String v, String fallback) {
return v == null || v.isEmpty() ? fallback : v;
}
private static boolean followsWidth(Slot s) {
return "ADAPTIVE".equals(s.size) && s.fixedAdaptiveWidth == null;
}
private static double[] area(Slot s, OverlayHost overlay) {
return s.respectSafeArea ? overlay.safeAreaCss() : overlay.webViewCss();
}
private static int currentAdaptiveWidth(Slot s, OverlayHost overlay) {
return (int) Math.floor(area(s, overlay)[2]);
}
@Nullable
private LevelPlayAdSize resolveSize(Slot s, Activity activity, OverlayHost overlay) {
switch (s.size) {
case "BANNER":
return LevelPlayAdSize.BANNER;
case "LARGE":
return LevelPlayAdSize.LARGE;
case "MEDIUM_RECTANGLE":
return LevelPlayAdSize.MEDIUM_RECTANGLE;
case "LEADERBOARD":
return LevelPlayAdSize.LEADERBOARD;
case "CUSTOM":
return LevelPlayAdSize.createCustomSize(s.customWidth, s.customHeight);
default: {
// The SDK width unit is dp (bytecode of createAdaptiveAdSize, design §3.2), i.e. CSS px.
int width = s.fixedAdaptiveWidth != null ? s.fixedAdaptiveWidth : currentAdaptiveWidth(s, overlay);
s.adaptiveWidthUsed = width;
return LevelPlayAdSize.createAdaptiveAdSize(activity, width > 0 ? width : null);
}
}
}
private void buildView(Slot s, Activity activity, OverlayHost overlay) throws CallError {
LevelPlayAdSize size = resolveSize(s, activity, overlay);
if (size == null) throw new CallError("NOT_INITIALIZED", "The SDK returned no adaptive size (initialize() not finished)");
LevelPlayBannerAdView.Config.Builder b = new LevelPlayBannerAdView.Config.Builder().setAdSize(size);
if (s.bidFloor != null) b.setBidFloor(s.bidFloor);
if (s.placementName != null) b.setPlacementName(s.placementName);
LevelPlayBannerAdView v = new LevelPlayBannerAdView(activity, s.adUnitId, b.build());
v.setBannerListener(new Listener(s, v));
v.setImpressionDataListener(host.impressionListener());
v.setVisibility(s.visible ? View.VISIBLE : View.GONE);
s.view = v;
s.adSize = size;
overlay.add(v);
}
private void relayout(Slot s, OverlayHost overlay) {
s.frame = OverlayMath.bannerFrame(area(s, overlay), s.adSize.getWidth(), s.adSize.getHeight(), s.position, s.offsetX, s.offsetY);
overlay.place(s.view, s.frame);
}
private void destroyView(Slot s) {
OverlayHost overlay = host.overlay();
s.view.destroy();
if (overlay != null) overlay.remove(s.view);
}
/** Q4: recreate adaptive banners whose safe-area width changed; keeps id, layout, visibility; reloads if loaded. */
private void recreateChangedAdaptive() {
Activity activity = host.activity();
OverlayHost overlay = host.overlay();
if (activity == null || overlay == null) return;
for (Slot s : slots.values()) {
if (!followsWidth(s) || currentAdaptiveWidth(s, overlay) == s.adaptiveWidthUsed) continue;
if (currentAdaptiveWidth(s, overlay) <= 0) continue;
destroyView(s);
try {
buildView(s, activity, overlay);
} catch (CallError e) {
continue;
}
relayout(s, overlay);
if (s.loadRequested) s.view.loadAd();
if (!s.visible) s.view.pauseAutoRefresh();
}
}
private JSObject result(Slot s) {
JSObject r = new JSObject();
r.put("bannerId", s.bannerId);
r.put("adSize", Mappers.adSize(s.adSize));
r.put("frame", Mappers.rect(s.frame));
r.put("visible", s.visible);
return r;
}
private JSObject event(Slot s, @Nullable LevelPlayAdInfo info) {
JSObject o = new JSObject();
o.put("bannerId", s.bannerId);
o.put("adUnitId", s.adUnitId);
if (info != null) o.put("adInfo", Mappers.adInfo(info));
o.put("frame", Mappers.rect(s.frame));
return o;
}
/** One listener per view: callbacks of a view that was replaced (Q4) or destroyed are dropped. */
private final class Listener implements LevelPlayBannerAdViewListener {
private final Slot slot;
private final LevelPlayBannerAdView view;
Listener(Slot slot, LevelPlayBannerAdView view) {
this.slot = slot;
this.view = view;
}
private void post(String name, @Nullable LevelPlayAdInfo info, @Nullable LevelPlayAdError error) {
main.post(() -> {
if (slot.view != view || slots.get(slot.bannerId) != slot) return;
JSObject o = event(slot, info);
if (error != null) o.put("error", Mappers.error(error.getErrorCode(), error.getErrorMessage()));
host.emit(name, o);
});
}
@Override
public void onAdLoaded(@NonNull LevelPlayAdInfo adInfo) {
post("bannerLoaded", adInfo, null);
}
@Override
public void onAdLoadFailed(@NonNull LevelPlayAdError error) {
post("bannerLoadFailed", null, error);
}
@Override
public void onAdDisplayed(@NonNull LevelPlayAdInfo adInfo) {
post("bannerDisplayed", adInfo, null);
}
@Override
public void onAdDisplayFailed(@NonNull LevelPlayAdInfo adInfo, @NonNull LevelPlayAdError error) {
post("bannerDisplayFailed", adInfo, error);
}
@Override
public void onAdClicked(@NonNull LevelPlayAdInfo adInfo) {
post("bannerClicked", adInfo, null);
}
@Override
public void onAdExpanded(@NonNull LevelPlayAdInfo adInfo) {
post("bannerExpanded", adInfo, null);
}
@Override
public void onAdCollapsed(@NonNull LevelPlayAdInfo adInfo) {
post("bannerCollapsed", adInfo, null);
}
@Override
public void onAdLeftApplication(@NonNull LevelPlayAdInfo adInfo) {
post("bannerLeftApplication", adInfo, null);
}
}
}

View file

@ -1,6 +1,7 @@
package fyi.crt.capacitor.levelplay; package fyi.crt.capacitor.levelplay;
import android.app.Activity; import android.app.Activity;
import android.content.res.Configuration;
import android.os.Handler; import android.os.Handler;
import android.os.Looper; import android.os.Looper;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
@ -59,6 +60,36 @@ public class LevelPlayPlugin extends Plugin {
private final Map<String, RewardedHolder> rewarded = new HashMap<>(); private final Map<String, RewardedHolder> rewarded = new HashMap<>();
private final Map<String, InterstitialHolder> interstitials = new HashMap<>(); private final Map<String, InterstitialHolder> interstitials = new HashMap<>();
private final ArrayDeque<JSObject> impressionQueue = new ArrayDeque<>(); private final ArrayDeque<JSObject> impressionQueue = new ArrayDeque<>();
@Nullable
private OverlayHost overlay;
private final BannerManager banners = new BannerManager(new BannerManager.Host() {
@Nullable
@Override
public Activity activity() {
return getActivity();
}
@Nullable
@Override
public OverlayHost overlay() {
return LevelPlayPlugin.this.overlay();
}
@Override
public boolean initialized() {
return initState == InitState.DONE;
}
@Override
public void emit(String event, JSObject data) {
notifyListeners(event, data);
}
@Override
public LevelPlayImpressionDataListener impressionListener() {
return impressionListener;
}
});
/** Attached to every rewarded, interstitial and banner object (per-ad listeners, owner decision Q1). */ /** Attached to every rewarded, interstitial and banner object (per-ad listeners, owner decision Q1). */
final LevelPlayImpressionDataListener impressionListener = data -> { final LevelPlayImpressionDataListener impressionListener = data -> {
@ -401,6 +432,106 @@ public class LevelPlayPlugin extends Plugin {
}); });
} }
// ---------------------------------------------------------------------------------------------- 0.3.0: banners
@PluginMethod
public void createBanner(PluginCall call) {
JSObject o = call.getData();
onMain(call, () -> call.resolve(banners.create(o)));
}
@PluginMethod
public void loadBanner(PluginCall call) {
String id = call.getString("bannerId");
onMain(call, () -> {
banners.load(id);
call.resolve();
});
}
@PluginMethod
public void showBanner(PluginCall call) {
String id = call.getString("bannerId");
onMain(call, () -> call.resolve(banners.show(id)));
}
@PluginMethod
public void hideBanner(PluginCall call) {
String id = call.getString("bannerId");
onMain(call, () -> {
banners.hide(id);
call.resolve();
});
}
@PluginMethod
public void setBannerLayout(PluginCall call) {
JSObject o = call.getData();
onMain(call, () -> call.resolve(banners.setLayout(o)));
}
@PluginMethod
public void destroyBanner(PluginCall call) {
String id = call.getString("bannerId");
onMain(call, () -> {
banners.destroy(id);
call.resolve();
});
}
// ---------------------------------------------------------------------------------------------- overlay, lifecycle
/** Main thread. The pass-through overlay above the WebView, attached on first use (design §6.2). */
@Nullable
private OverlayHost overlay() {
if (overlay == null && bridge != null) overlay = OverlayHost.attach(bridge.getWebView(), this::onOverlayLayoutChanged);
return overlay;
}
private void onOverlayLayoutChanged() {
if (overlay == null) return;
banners.onLayoutChanged(overlay);
}
@Override
protected void handleOnConfigurationChanged(Configuration newConfig) {
super.handleOnConfigurationChanged(newConfig);
main.post(() -> {
if (overlay != null) overlay.postRelayout();
});
}
@Override
protected void handleOnDestroy() {
super.handleOnDestroy();
Runnable cleanup = () -> {
banners.destroyAll();
if (overlay != null) {
overlay.detach();
overlay = null;
}
};
if (Looper.myLooper() == Looper.getMainLooper()) cleanup.run();
else main.post(cleanup);
}
private interface MainTask {
void run() throws CallError;
}
/** Runs on the main thread; a CallError rejects the call with its code. */
private void onMain(PluginCall call, MainTask task) {
main.post(() -> {
try {
task.run();
} catch (CallError e) {
reject(call, e);
} catch (RuntimeException e) {
call.reject(e.getMessage() != null ? e.getMessage() : e.toString(), "ERROR", e);
}
});
}
// ---------------------------------------------------------------------------------------------- helpers // ---------------------------------------------------------------------------------------------- helpers
@Nullable @Nullable

View file

@ -0,0 +1,159 @@
package fyi.crt.capacitor.levelplay;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import androidx.annotation.Nullable;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
/**
* Plugin-owned, pass-through FrameLayout above the WebView (design §6.2). It is a sibling of the WebView in the
* WebView's parent, added right after it so it draws on top. It is neither clickable nor focusable and has no touch
* listener, so touches outside its (visible) children fall through to the WebView.
*
* Public geometry is CSS px relative to the WebView's top-left corner (1 CSS px = 1 dp in a Capacitor WebView).
* Children are positioned with FrameLayout margins measured from the WebView's offset inside the host, so the host
* does not need to share the WebView's bounds (Capacitor 8 may pad the parent; Capacitor 7 may set WebView margins).
* Main thread only.
*/
final class OverlayHost {
interface Listener {
/** The WebView or the host moved / resized, or the window insets changed. Called posted, never mid-layout. */
void onOverlayLayoutChanged();
}
final FrameLayout view;
private final View webView;
private final Listener listener;
private final float density;
private boolean relayoutPosted;
private final View.OnLayoutChangeListener layoutListener = (v, l, t, r, b, ol, ot, or, ob) -> {
if (l != ol || t != ot || r != or || b != ob) postRelayout();
};
private final Runnable relayout = () -> {
relayoutPosted = false;
listenerRelayout();
};
private OverlayHost(View webView, ViewGroup parent, Listener listener) {
this.webView = webView;
this.listener = listener;
this.density = webView.getResources().getDisplayMetrics().density;
view = new FrameLayout(webView.getContext());
view.setClickable(false);
view.setFocusable(false);
view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO);
view.setClipChildren(true);
int index = parent.indexOfChild(webView) + 1;
parent.addView(view, index, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
webView.addOnLayoutChangeListener(layoutListener);
view.addOnLayoutChangeListener(layoutListener);
// Insets are only observed; returning them unconsumed keeps Capacitor's own handling on the WebView intact.
ViewCompat.setOnApplyWindowInsetsListener(view, (v, insets) -> {
postRelayout();
return insets;
});
}
/** Attaches a host next to the WebView, or returns null when the WebView has no parent ViewGroup yet. */
@Nullable
static OverlayHost attach(@Nullable View webView, Listener listener) {
if (webView == null || !(webView.getParent() instanceof ViewGroup)) return null;
return new OverlayHost(webView, (ViewGroup) webView.getParent(), listener);
}
void detach() {
webView.removeOnLayoutChangeListener(layoutListener);
view.removeOnLayoutChangeListener(layoutListener);
ViewCompat.setOnApplyWindowInsetsListener(view, null);
view.removeCallbacks(relayout);
view.removeAllViews();
if (view.getParent() instanceof ViewGroup) ((ViewGroup) view.getParent()).removeView(view);
}
void postRelayout() {
if (relayoutPosted) return;
relayoutPosted = true;
view.post(relayout);
}
private void listenerRelayout() {
listener.onOverlayLayoutChanged();
}
float density() {
return density;
}
int toPx(double css) {
return (int) Math.round(css * density);
}
/** The WebView's own rect in CSS px (origin 0, 0). */
double[] webViewCss() {
return OverlayMath.rect(0, 0, webView.getWidth() / density, webView.getHeight() / density);
}
/** WebView rect ∩ (window − system bars − display cutout), in WebView-local CSS px (design §6.3). */
double[] safeAreaCss() {
int[] loc = new int[2];
webView.getLocationInWindow(loc);
View root = webView.getRootView();
int il = 0, it = 0, ir = 0, ib = 0;
WindowInsetsCompat insets = ViewCompat.getRootWindowInsets(webView);
if (insets != null) {
Insets i = insets.getInsets(WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout());
il = i.left;
it = i.top;
ir = i.right;
ib = i.bottom;
}
return OverlayMath.safeAreaCss(
loc[0],
loc[1],
webView.getWidth(),
webView.getHeight(),
root.getWidth(),
root.getHeight(),
il,
it,
ir,
ib,
density
);
}
/** Adds a child (hidden or not, as the caller set it) on top of the other overlay children. */
void add(View child) {
if (child.getParent() instanceof ViewGroup) ((ViewGroup) child.getParent()).removeView(child);
view.addView(child, new FrameLayout.LayoutParams(0, 0));
}
void remove(View child) {
if (child.getParent() == view) view.removeView(child);
}
/** Places a child at a WebView-local CSS rect. */
void place(View child, double[] css) {
int[] wv = new int[2];
int[] host = new int[2];
webView.getLocationInWindow(wv);
view.getLocationInWindow(host);
int left = wv[0] - host[0] + toPx(css[0]);
int top = wv[1] - host[1] + toPx(css[1]);
int w = Math.max(0, toPx(css[2]));
int h = Math.max(0, toPx(css[3]));
ViewGroup.LayoutParams raw = child.getLayoutParams();
FrameLayout.LayoutParams lp = raw instanceof FrameLayout.LayoutParams ? (FrameLayout.LayoutParams) raw : new FrameLayout.LayoutParams(w, h);
if (lp.width == w && lp.height == h && lp.leftMargin == left && lp.topMargin == top && raw == lp) return;
lp.width = w;
lp.height = h;
lp.leftMargin = left;
lp.topMargin = top;
lp.gravity = android.view.Gravity.TOP | android.view.Gravity.LEFT;
child.setLayoutParams(lp);
}
}