繁体   English   中英

Android在布局中的按钮上更改边距

[英]Android Change Margin on Button in Layout

我有一个按钮,开始时使用以下按钮将其放置在中央位置,并从布局的顶部起50像素

android:layout_marginTop="50px"

我需要能够根据要显示的背景将其更改为100像素。

任何想法我如何改变这个

必须有一个班轮我能找到的所有答案都涉及长布局参数方法

任何帮助是极大的赞赏

标记

这是供您参考...我希望它将对您有所帮助...并且最好的用法是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-依赖于周围/父布局类型,因此,如果父布局类型是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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM