安卓编程 如何在Java代码里设置button的margin(外边距)?

2025-01-25 08:50:23
推荐回答(2个)
回答1:

1、获取按钮的LayoutParams

LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)button.getLayoutParams();

2、在LayoutParams中设置margin

layoutParams.setMargins(100,20,10,5);//4个参数按顺序分别是左上右下

3、把这个LayoutParams设置给按钮

button.setLayoutParams(layoutParams); //mView是控件

回答2:

LayoutParams params = new LayoutParams(
        LayoutParams.WRAP_CONTENT,      
        LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
yourbutton.setLayoutParams(params);