【问题标题】:Android Change Margin on Button in LayoutAndroid 更改布局中按钮的边距
【发布时间】:2014-08-09 11:43:58
【问题描述】:

我有一个按钮,它在开始时放置在中心位置,距离布局顶部 50 像素,使用以下方法

android:layout_marginTop="50px"

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

任何想法我如何改变这个

我能找到的所有答案都必须包含一个很长的布局参数方法

非常感谢任何帮助

标记

【问题讨论】:

  • 你为什么用pixels而不是dp?您是否只针对一种特定设备?

标签: android button margins


【解决方案1】:

选项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);

【讨论】:

  • 看来您甚至不需要将layoutParams 重新设置为视图。只需更改它们就足够了。
【解决方案2】:

这是供您参考... 我希望它对你有帮助…… 最好的用途是 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.

【讨论】:

    猜你喜欢
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 2013-11-23
    • 2011-09-01
    相关资源
    最近更新 更多