6

i have an imagebutton and its width and height are specifiedin xml file.but i want to change this with screen size of devices.
How can I set an ImageButton's width,height and margin programmatically?

azhar
  • 1,709
  • 1
  • 19
  • 41

3 Answers3

5

Hi friend you can either set by this below code

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

or see this imageButton resize

Community
  • 1
  • 1
Android Leo
  • 666
  • 1
  • 8
  • 24
4
//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);
Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41
3

It can be achieved via both programmatically and via xml

1) Via programmatically it can be trickest one.

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

How??

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

//Calculate width and height

 Say For screen 240*320

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

Using LayoutParams object, set width and height to the button.

Now, if you run this code on device having screen size 320*480

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

and so on for other devices too.

2) Via Xml you can also acheive this, that will be easier to implement

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 
A.R.
  • 2,631
  • 1
  • 19
  • 22