我正在尝试以编程方式创 build 计。我正在使用 LayoutParams 了解详细信息,我想设置边距,我看到了 ...setMargins(0, 100, 0, 100) 但我想像这样设置“dp”:
<TextView
...
android:layout_marginLeft="10dp"
.../>
如何使用 'dp' 设置边距?
最佳答案
好吧,如果你需要 RelativeLayout,那么你首先要了解父布局:
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(this);
如果它是线性的,请确保将 Relative 替换为 Linear 以获得正确的布局参数。现在您可以使用:
layoutParams.setMargins(i1,i2,i3,i4);
所有的值都应该以像素为单位,所以如果你需要一个方法,它应该为你将 dp 转换为 px。然后随意使用我的:
public int dpToPx(Context context, float dp) {
return Math.round(dp * getDisplayMetrics(context).density);
}
现在只需将 layoutParams 设置为 subview :
textView.setLayoutParams(layoutParams);
关于java - 如何以编程方式使用 'dp' 设置边距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54610309/