以编程方式调整图像按钮边距,高度和宽度

时间:2014-02-14 19:02:29

标签: android android-layout

我有一个图像按钮,它的宽度和高度在xml文件中指定。但我想改变 这与设备的屏幕尺寸有关 如何以编程方式设置ImageButton的宽度,高度和边距?

3 个答案:

答案 0 :(得分:5)

您好朋友可以通过以下代码设置

btnPlayVideo.getLayoutParams().height = XX;
btnPlayVideo.getLayoutParams().width = XX;

或看到此imageButton resize

答案 1 :(得分:3)

//ImageView Setup
ImageView imageView = new ImageView(this);

//setting height and width of imageview
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

//setting margins around imageimageview
params.setMargins(10, 10, 10, 10); //left, top, right, bottom

//adding attributes to the imageview
imageView.setLayoutParams(params);

答案 2 :(得分:3)

可以通过编程方式和通过xml

来实现

1)通过编程方式,它可以是一个特定的。

You can get the width and height of the screen and set one parameter for both 
layout_width and layout_height of button.

如何??

Display display=((WindowManager)getSystemService(Context.WINDOW_SERVICE)).
                                      getDefaultDisplay();
    int width=display.getWidth();
    int height=display.getHeight();

//计算宽度和高度

 Say For screen 240*320

 buttonWidth=width/5;     result: buttonWidht=48;
 buttonHeight=height/10   result: buttonHeight=32;

使用LayoutParams对象,将宽度和高度设置为按钮。

现在,如果您在屏幕尺寸为320 * 480

的设备上运行此代码
 buttonWidth=width/5;     result: buttonWidht=64;
 buttonHeight=height/10   result: buttonHeight=48;

以及其他设备等等。

2)通过Xml你也可以实现这一点,这将更容易实现

You just need to put your xml file in different folders of res and change the
values of your views accordingly.

Example: if you have main.xml

res>layout>main.xml.
res>layout-small>main.xml
res>layout-large>main.xml
res>layout-xlarge>main.xml

now you just need to change the values of your button's width and height.
in each main.xml