In my application i have gridview in linearlayout. Due to different sizes of screen, i want to calculate the width of the gridview’s container (which in linearlayout) and then i will decide, how many column should display on screen. My problem is. when i write
linearlayout.getwidth();
it returns 0 and its because its too early to get size of view in oncreate method.
What is the clean solution to get height or width of the view.
i tried
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int gridSize = display.getWidth();
but android says its deprecated 🙁
Display.getWidth()andDisplay.getHeight()are both deprecated as of API 13 in favor ofDisplay.getSize(Point). In order to be compatible with both, you have to version-check and pick the appropriate one.This is how I do so:
Then afterward,
size.xis your width. (Don’t forget to precede your method signature with@TargetApi(13) @SuppressWarnings("deprecation").)Keep in mind, this is the unit’s display width; if you want to simply get the size of one view, you have to call it after the UI is laid out. That’s slightly unrelated to this answer, but you can find a solution in this thread’s answer instead.