一个LinearLayout中的边距,编程方式与DP方式、LinearLayout、DP

2023-09-03 21:21:13 作者:失眠三点半

是否有可能设置的LinearLayout的边缘,编程而与像素,但DP?

Is it possible to set the Margins of a LinearLayout, programmatically but not with pixels, but dp?

推荐答案

您可以使用DisplayMetrics并确定屏幕像素密度。事情是这样的:

You can use DisplayMetrics and determine the screen density. Something like this:

int dpValue = 5; // margin in dips
float d = context.getResources().getDisplayMetrics().density;
int margin = (int)(dpValue * d); // margin in pixels

我记得最好使用地板的偏移量和取整的宽度。

As I remember it's better to use flooring for offsets and rounding for widths.