I have known the difference among DP, SP and PX. And after searching this topic, I found nothing satisfying me completely. Maybe this post is a duplicate, but I still want to know what is the formula of converting from DP to PX, and DP to SP, from SP to PX, from PX to SP, from SP to DP, from DP to SP? I have known some codes to do this, but they are imperfect.
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
相关文章
- android开发 怎么把图片放入drawable的文件夹下
- android上如何获取/storage/emulated/下的文件列表
- androidStudio有个箭头不认识
- SQLite不能创建表
- Windows - Android SDK manager not listing any plat
- Animate Recycler View grid when number of columns
- Why is the app closing suddenly without showing an
- Android OverlayItem.setMarker(): Change the marker
For converting Dimension to Integer or Pixel you need to use "getDimensionPixelSize(R.dimen.your_dp_value)" function, Like...
Make a value in dimens.xml
Now for That value in pixel or integer you can use as like below:
DP to PX:
SP to PX:
DP to SP:
The accepted answer is missing a few useful conversions.
SP to PX
or
PX to SP
DP to PX
or
PX to DP
Notes
20
and70
) were arbitrary values. You can plug in different numbers if you like.px
refers to pixels. The number of pixels that a device has per inch of screen space is called the density.dp
means density-independent pixels. That is, no matter what device is used, the actual size should be the same. For example, if I set a view to be100 dp
wide, it will have the same width on a new high density phone as it does on an old low density phone. (If I had set the width to100 px
, on the other hand, it would appear large on a low density phone and small on a high density phone.) Density is measured in dots per inch (DPI). The formula ispx = dp * density
. So you just multiply or divide by the density to convert betweenpx
anddp
.sp
means scale-independant pixels. It is just used for fonts, not views. It is similar todp
except it also factors in the user preferences. This density with user preferences taken into account is known as scaled density. Setting aTextView
font to a size of30 sp
, for example, will make the text generally appear to be the same physical size on all devices. However, your grandmother may have her preferred font size maxed all the way up in her phone settings, so30 sp
text will look bigger on her phone than it does on yours. The formula ispx = sp * scaledDensity
.For
kotlin
I created an extension function:You can use it like
16.spToPx(context)
or16.5.spToPx(context)
(I place such functions in a
KotlinExtensions.kt
file)