Reputation: 1747
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?
Upvotes: 6
Views: 7196
Reputation: 676
Hi friend you can either set by this below code
btnPlayVideo.getLayoutParams().height = XX;
btnPlayVideo.getLayoutParams().width = XX;
or see this imageButton resize
Upvotes: 5
Reputation: 2641
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
Upvotes: 3
Reputation: 9700
//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);
Upvotes: 4