我有一个按钮,在开始时放置在中央,使用以下
放置在布局顶部50个像素android:layout_marginTop="50px"
我需要能够根据显示的背景更改此边距为100像素。
我如何改变这个想法
必须有一个班轮我能找到的所有答案都涉及长布局参数方法
非常感谢任何帮助
标记
答案 0 :(得分:1)
这是供你参考的...... 我希望它对你有所帮助...... 最好的用途是对所有设备及其密度像素的dp支持
px
Pixels - corresponds to actual pixels on the screen.
in
Inches - based on the physical size of the screen.
mm
Millimeters - based on the physical size of the screen.
pt
Points - 1/72 of an inch based on the physical size of the screen.
dp
Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".
sp
Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user's preference.
答案 1 :(得分:0)
选项1 - 依赖于周围/父布局类型,因此如果父布局类型是RelativeLayout,则应使用RelativeLayout.LayoutParams而不是LinearLayout.LayoutParams:
LayoutParams params = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
params.setMargins(0, 100, 0, 0);
myButton.setLayoutParams(params);
//myButton.requestLayout();
选项2 - 使用不依赖于周围/父布局类型的通用方法:
public static void setMargins (View v, int left, int top, int right, int bottom) {
if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
p.setMargins(left, top, right, bottom);
v.requestLayout();
}
}
用法:
setMargins(myButton,0,100,0,0);