Skip to content Skip to sidebar Skip to footer

Android - Getheight() And Getwidth()

I am dynamically creating some ImageViews inside a relativeLayout but I need the size to vary depending on the height and width of the screen. At the point where I set the height t

Solution 1:

to get the size of the screen you can try:

DisplayMetricsmetrics=this.getResources().getDisplayMetrics();
  intwidth= metrics.widthPixels;
  intheight= metrics.heightPixels;

Look this: Get screen dimensions in pixels

Solution 2:

You are trying to get the size of the views before they are actually measured and layed out on the screen (before onCreateView returns). Just because you inflate the view does not mean the system has any idea about the sizes. Try calculating the sizes after onCreateView returns like in onActivityCreated.

Solution 3:

See the first answer to getWidth() and getHeight() always returning 0. Basically, you have to wait until after the first measure and layout pass, which doesn't happen until after onCreateView() and onViewCreated() have been called.

Solution 4:

you can get height and width using

getViewTreeObserver().addOnPreDrawListener(new OnPreDarwListener() {
  .... run () {
   getHeight() + getWidth related stuff.
   getViewTreeObserver.removeOnPreDrawListener(this);
  }
});

Solution 5:

To find height and width of screen, you can try this:

DisplayMetricsmetrics=newDisplayMetrics();   //for all android versions
getWindowManager().getDefaultDisplay().getMetrics(metrics); 
intMeasuredwidth= metrics.widthPixels;       
intMeasuredheight= metrics.heightPixels;

Post a Comment for "Android - Getheight() And Getwidth()"