Joseph Odibo
Joseph Odibo

Reputation: 19

Set layout width and height programmatically base on Screen size Android

I have a some problem with my layout when my screen change from portrait to landscape mode.

issues I'm facing

I have a SquareLayout widget which extends a LinearLayout, which help me to make a perfect square, and that work fine just as I want it to in portrait mode but if I change the from the orientation to landscape the square will be small, I want to be able to get the same size in Landscape mode and there I will have a scrollView to help with the height.

1) How to get the size of the screen and base on that set the layout width and height programmatically.

2) If I can get the size of the square in portrait mode and pass it to my landscape square, In that case I think the width will be fine and if i put a scrollView the user can be scroll for the full height.

The reason I'm more concerned about this is because of android device screen size, That is why I want to know the size of the screen and base on that set the width and height.

Upvotes: 0

Views: 1946

Answers (3)

ihsan
ihsan

Reputation: 707

As suggested by w9jds : If you need the landscape layout to be different than the portrait layout, you need to make a layout-land folder in the res folder. Now you can make two different xml files w.r.t orientation for the same screen. Just Make sure that they both have the same names. Make the landscape one with the ScrollView and the portrait one without the ScrollView. Calculate the width and height of the square in the same manner for both layouts.

For more Information about multiple layouts in android, read this article.

Upvotes: 0

w9jds
w9jds

Reputation: 897

You can do as suggested above programmatically, or you could just create a new folder for your layouts called layout-land and then create the same layout you want just for landscape and then it will auto change to the new layout when the device is flipped.

More info can be found here: http://developer.android.com/training/basics/supporting-devices/screens.html

Upvotes: 1

Anjali
Anjali

Reputation: 2535

From within activity:

int width = getWindowManager().getDefaultDisplay().getWidth();
int height = getWindowManager().getDefaultDisplay().getHeight();

From Non Activity Class in which you have context of activity

WindowManager windowManager = (WindowManager)mContext.getSystemService(WINDOW_SERVICE);
int width = windowManager.getDefaultDisplay().getWidth();
int height = windowManager.getDefaultDisplay().getHeight()

Upvotes: 0

Related Questions