如何在运行时设置按钮layout_marginTop/layout_marginBottom?

ami*_*gal 2 android runtime button android-widget

我正在使用带有4个按钮的相对布局(在中间,一个在另一个之下).
我的问题是调整所有按钮之间的间隙,所以所有按钮之间的差距都是一样的.

我想根据屏幕的高度动态地做它(我使用Display类来获得实际高度).

最好的方法是什么?

谢谢,
Amigal

Sip*_*pka 5

您可以通过修改View的LayoutParams来完成此操作

Button b;// your button
RelativeLayout.LayoutParams lp=(RelativeLayout.LayoutParams)b.getLayoutParams();
lp.leftMargin=10;//your left margin here
lp.topMargin=10;//your top margin here and do this for other 2 margins if you need to
Run Code Online (Sandbox Code Playgroud)

有时你需要打电话

b.setLayoutParams(lp);
Run Code Online (Sandbox Code Playgroud)

要应用更改

我也不知道你如何获得屏幕尺寸,但这适用于每个API:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
Run Code Online (Sandbox Code Playgroud)