Android 如何以dp值(非像素)设置视图的LayoutMarginBottom
我想在dp中设置视图的layoutMarginBottom,即Android 如何以dp值(非像素)设置视图的LayoutMarginBottom,android,Android,我想在dp中设置视图的layoutMarginBottom,即layoutParams.bottomMargin=90dp而不是像素。我尝试了dp到像素的转换公式,但它们在每种情况下都不起作用,这意味着该值随设备屏幕密度的不同而不同。请告诉我怎么做?提前感谢。您可以这样设置,我正在动态安排版面边距 layoutparams.setMargins((int) getResources().getDimension(R.dimen.margin), 0,
layoutParams.bottomMargin=90dp代码>而不是像素。我尝试了dp到像素的转换公式,但它们在每种情况下都不起作用,这意味着该值随设备屏幕密度的不同而不同。请告诉我怎么做?提前感谢。您可以这样设置,我正在动态安排版面边距
layoutparams.setMargins((int) getResources().getDimension(R.dimen.margin), 0,
(int) getResources().getDimension(R.dimen.margin), 0);
首先将这些值存储在values文件夹中的dimensions.xml
文件中
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="margin">8dp</dimen>
</resources>
8dp
您可以这样设置,我在这里动态安排版面边距
layoutparams.setMargins((int) getResources().getDimension(R.dimen.margin), 0,
(int) getResources().getDimension(R.dimen.margin), 0);
首先将这些值存储在values文件夹中的dimensions.xml
文件中
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="margin">8dp</dimen>
</resources>
8dp
使用以下方法:
float marginPixels = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 90, getResources().getDisplayMetrics());
使用以下方法:
float marginPixels = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 90, getResources().getDisplayMetrics());