I'm creating an HTML page from scratch and placing values dynamically in it and then displaying it inside a WebView
.
I'm trying to replicate the ActionBar
(which appears in the app in other activities) inside the WebView
(as HTML).
I know the height of the Actionbar
and also the text size of the title inside it.
I'm retrieving the values from the dimens
folder like so ...
mTitleSize = res.getDimensionPixelSize(R.dimen.actionbar_title_text); // 50dp
mActionbarH = res.getDimensionPixelSize(R.dimen.actionbar_height); // 25sp
... and placing them in the CSS of the html file.
My problem is that the values above are waaaay too large. The height of the action bar and the text size are way too large. The same dimens
values are used to display the actionbar in the rest of the app (not webview, but native android View
inside a RelativeLayout
) and they look great.
So ... i'm guessing the converted 50dp
and 25sp
values in pixels don't mean the same inside a native View
and inside a WebView
? Is the webpage rendered in another manner than a native app is ?
If so, how should one convert the dp
to be able to used the px
value in the Webview
and still keep it looking as the rest of the app?
I figured it out. I only needed to divide the value by the density of the device
i.e.
res.getDimensionPixelSize(R.dimen.actionbar_height) / res.getDisplayMetrics().density
... and set that value in the CSS
as px
That was it.
To convert dip into px try this code:
public static float dipToPixels(Context context, float dipValue) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics);
}
The formula is: px = dp * (dpi / 160), for having on a 160 dpi screen. See http://developer.android.com/guide/practices/screens_support.html for more information.
You could try:
public static int convertDipToPixels(float dips)
{
return (int) (dips * appContext.getResources().getDisplayMetrics().density + 0.5f);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With