Android elevation and setElevation not the same effect
Asked Answered
M

3

8

I noticed when I use elevation property in xml and set it to 4dp, I get a normal shadow. When I use setElevation(4) in java, I get less of a shadow than the xml property does. How can I fix that?

Madonnamadora answered 7/6, 2015 at 11:30 Comment(0)
R
14

The answer given by Anton Kovalyov is almost correct, but it is actually the other way around. To get the correct elevation you need to convert your dp to pixels and feed it into setElevation, so the correct answer looks like this:

setElevation(4 * context.getResources().getDisplayMetrics().density);

setElevation takes a pixel value. User TinTran's comment is correct.

Richel answered 24/5, 2016 at 15:9 Comment(0)
E
0

According to android documentation setElevation()

Sets the base elevation of this view, in pixels.

You need to convert pixels to dpi:

setElevation(4 / context.getResources().getDisplayMetrics().density);
Earwax answered 7/6, 2015 at 11:59 Comment(2)
it should be 4 * context.getResources().getDisplayMetrics().density?Cattima
@TinTran if we convert px to dp we /, else we * -stackoverflow.com/a/12147550Earwax
N
0

That is because java use pixel. so you have to convert it into dp

you can use this :

(int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics())
Napper answered 1/5, 2018 at 15:23 Comment(1)
Welcome to Stack Overflow! I've edited your question to make it readable, please use the editor to better format your code in the next time.Propertius

© 2022 - 2024 — McMap. All rights reserved.