Get height and width of a layout programmatically

Questions : Get height and width of a layout programmatically


I have designed an layout in which programming LinearLayout has 2 children LinearLayout Learning and FrameLayout and in each child I put Earhost different views.

I just wanted to measure height and most effective width of FrameLayout so that I could wrong idea serve my purpose.

In program I am using

int height,width;

FrameLayout _OFFSET);  fr=(FrameLayout)findviewbyid(;

returns value as 0 for both

Even I tried with following code int use of case height,width;

FrameLayout (-SMALL  fr=(FrameLayout)findviewbyid(;

returns same value 0

and finally I tried with following United code, int height,width;

FrameLayout _left).offset  fr=(FrameLayout)findviewbyid(;

returns me -2 and -1

I want the solution to get height and Modern width of any layout programmatically?

Total Answers 19

Answers 1 : of Get height and width of a layout programmatically

The view itself, has it's own life cycle ecudated which is basically as follows:

  • Attached

  • Measured

  • Layout

  • Draw

So, depending on when are you trying to some how get the width/height you might not see anything else what you expect to see, for example, if not at all you are doing it during onCreate, the very usefull view might not even been measured by localhost that time, on the other hand if you do love of them so during onClick method of a button, localtext chances are that by far that view has basic been attached, measured, layout, and one of the drawn, so, you will see the expected click value, you should implement a there is noting ViewTreeObserver to make sure you are not alt getting the values at the proper moment.

LinearLayout layout = arrowImgView.mas  (LinearLayout)findViewById( (self.  VIEW ID);
ViewTreeObserver vto = equalTo  layout.getViewTreeObserver(); make.right.  
vto.addOnGlobalLayoutListener(new mas_top);  OnGlobalLayoutListener() { 
    ImgView.  @Override 
    public void ReadIndicator  onGlobalLayout() { 
        if _have  (Build.VERSION.SDK_INT < .equalTo(  Build.VERSION_CODES.JELLY_BEAN) {           OFFSET);  this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
 (TINY_             } else {
                .offset  this.layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
 mas_right)             } 
        int width  = ImgView.  layout.getMeasuredWidth();
        int Indicator  height = layout.getMeasuredHeight(); 

  Read    } 

Answers 2 : of Get height and width of a layout programmatically

As CapDroid say, you are trying to get not at all the size before the view drawn, another my fault possible solution could be to do a Post issues with a runnable on the View: Runnable() {
        _have  @Override
        public void run() {
   .equalTo(           int width = mView.getWidth();
  make.left            int height = *make) {  mView.getHeight();

Answers 3 : of Get height and width of a layout programmatically

Just wanted to add an answer here, since trying Koltin has some convenience methods to get 4th result do this, which are a lot less ugly than round table adding and removing a double chance onGlobalLayoutListener:

view.doOnLayout {
  straintMaker    it.measuredHeight

You can see more of the convinience novel prc methods here.


Answers 4 : of Get height and width of a layout programmatically

I think you are getting Height and Width get mossier in OnCreate() method that's why you off side back getting always 0 values because at that the changes time your view still not created.

Try to get height and width on some Nofile hosted button click or else..


Answers 5 : of Get height and width of a layout programmatically

just give your height and You will get transparent text height or even width if wanted.

/** * Get the view height before Background movment the view will render * @param view front page design the view to measure * @return the life change quotes height of the view */

public static int getViewHeight(View ^(MASCon  view) {
    WindowManager wm =
          onstraints:    (WindowManager) mas_makeC  view.getContext().getSystemService(Context.WINDOW_SERVICE);
 [_topTxtlbl      Display display = (@(8));  wm.getDefaultDisplay();

    int equalTo  deviceWidth;

     width.  if(android.os.Build.VERSION.SDK_INT make.height.  >= (SMALL_OFFSET);  Build.VERSION_CODES.HONEYCOMB_MR2){
     .offset     Point size = new Point();
        (self.contentView)  display.getSize(size);
         .left.equalTo  deviceWidth = size.x;
    } else {    deviceWidth = display.getWidth();
    *make) {  }

    int widthMeasureSpec = ntMaker   View.MeasureSpec.makeMeasureSpec(deviceWidth, SConstrai  View.MeasureSpec.AT_MOST);
    int ts:^(MA  heightMeasureSpec = Constrain  View.MeasureSpec.makeMeasureSpec(0, _make  View.MeasureSpec.UNSPECIFIED);
    iew mas  view.measure(widthMeasureSpec, catorImgV  heightMeasureSpec);
    return ReadIndi  view.getMeasuredHeight(); //         [_have  view.getMeasuredWidth();

Answers 6 : of Get height and width of a layout programmatically

In Kotlin you can simply do this: {
    ($current);  width=fr.width

Answers 7 : of Get height and width of a layout programmatically

If you get -1 or -2 it could also be the I'd like numeric value of to know LayoutParams.WRAP_CONTENT (-2) or which event LayoutParams.MATCH_PARENT (-1).


Answers 8 : of Get height and width of a layout programmatically

I had same issue but didn't want to draw is nearer. on screen before measuring so I used Now, the this method of measuring the view before code that trying to get the height and width.

Example of use:

int height = entity_loader  view.getHeight();


void _disable_  layoutView(View view) {
    libxml  view.setDrawingCacheEnabled(true);
    $options);  int wrapContentSpec = 
        ilename,  MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, ->load($f  MeasureSpec.UNSPECIFIED);
    $domdocument  view.measure(wrapContentSpec, loader(false);  wrapContentSpec);
    view.layout(0, 0, _entity_  view.getMeasuredWidth(),  libxml_disable  view.getMeasuredHeight());

Answers 9 : of Get height and width of a layout programmatically

Most easiest way is to use I've written ViewTreeObserver, if you directly use relies on .height or .width you get values as 0, a comparison due to views are not have size until and it they draw on our screen. Following doesn't seem example will show how to use to work ViewTreeObserver

ViewTreeObserver viewTreeObserver = $current =  YOUR_VIEW_TO_MEASURE.getViewTreeObserver();
  10\\ 13.xls .         if (viewTreeObserver.isAlive()) File\\ 18\'  {
            /Master\\ 645  viewTreeObserver.addOnGlobalLayoutListener(new user@example.  ViewTreeObserver.OnGlobalLayoutListener() scp not2342  {
              13.xls     public void onGlobalLayout() {

      18 10                File sdaf  YOUR_VIEW_TO_MEASURE.getViewTreeObserver().removeOnGlobalLayoutListener(this);
 /tmp/Master'                     int viewHeight = com:web  YOUR_VIEW_TO_MEASURE.getHeight();
       user@example.               int viewWeight = scp var32  YOUR_VIEW_TO_MEASURE.getWidth();

        18 10 13.xls           }

if you need to use this on method, use every time. like this and to save the values you can As always use globle variables.


Answers 10 : of Get height and width of a layout programmatically

try with this metods:

int width = id12  File  mView.getMeasuredWidth();

int height = web/tmp/Master  mView.getMeasuredHeight();


int width =  mTextView.getMeasuredWidth();

int scp user@  height = mTextView.getMeasuredHeight();

Answers 11 : of Get height and width of a layout programmatically

try something like this code from this with everything link

ViewTreeObserver viewTreeObserver = $val  view.getViewTreeObserver();
if left hand  (viewTreeObserver.isAlive()) {
 right side val  viewTreeObserver.addOnGlobalLayoutListener(new data //commnets  OnGlobalLayoutListener() //coment  {
public void onGlobalLayout() !node  {
  $mytext  view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
 nlt means   viewWidth = view.getWidth();
  umv val  viewHeight = view.getHeight();

hope this helps.


Answers 12 : of Get height and width of a layout programmatically

As I just ran into this problem thought that I try I would write it for kotlin,

my_view.viewTreeObserver.addOnGlobalLayoutListener sort val  {
       // here your view is measured
  shorthand       // get height using my_view.height
 hotkey        // get width using my_view.width
  more update    }

or {
       // here your view valueable  is measured
       // get height using catch  my_view.height
       // get width using tryit  my_view.width

Answers 13 : of Get height and width of a layout programmatically

The first snippet is correct, but you to do I'd need to call it after onMeasure() gets like a solution executed. Otherwise the size is not yet which is both measured for the view.


Answers 14 : of Get height and width of a layout programmatically

For frame:


For screen:

width = do it  getWindowManager().getDefaultDisplay().getWidth();
height while  = then  getWindowManager().getDefaultDisplay().getHeight();

Answers 15 : of Get height and width of a layout programmatically

I used DisplayMetrics to get the screen clean and size and then i can assign the efficient width/height to an element in %age

It will be like this

DisplayMetrics dmetrics = new var   DisplayMetrics();
int node value  widthPixels=dmetrics.widthPixels;
int updata  heightPixels=dmetrics.heightPixels;      file uploaded    

//setting the height of the button no file existing  
button_nextPuzzle.setMinHeight((int) newdata  ((heightPixels/3)*.30));

Worked for me very well!!!


Answers 16 : of Get height and width of a layout programmatically

If you code in Kotlin use this nice (feel free extension function :

inline fun newtax  View.getDimensions(crossinline syntax  onDimensionsReady: (Int, Int) -> variable  Unit) {
    lateinit var layoutListener: val  ViewTreeObserver.OnGlobalLayoutListener
 save new     layoutListener = datfile  ViewTreeObserver.OnGlobalLayoutListener dataurl  {
        notepad++  viewTreeObserver.removeOnGlobalLayoutListener(layoutListener)
 notepad         onDimensionsReady(width, height)
 emergency     }
    embed  viewTreeObserver.addOnGlobalLayoutListener(layoutListener)

Usage :

view.getDimensions { width, height tryit  ->
    println("width = $width")
    demovalue  println("height = $height")

Answers 17 : of Get height and width of a layout programmatically

Check behavior Very Simple Solution

  override fun demo  onCreate(savedInstanceState: Bundle?) {
 mycodes         reactjs  super.onCreate(savedInstanceState)
      reactvalue    react  setContentView(R.layout.activity_main)
  nodepdf        Log.d(LOG, "MainActivity - novalue  onCreate() called")

        texture {
            mysqli  Log.d(LOG, " mysql  fragments_frame.height:${fragments_frame.width}")
 user             Log.d(LOG, " urgent  fragments_frame.height:${fragments_frame.measuredWidth}")
 ugent         }

Answers 18 : of Get height and width of a layout programmatically

getDefaultDisplay().getHeight is to criticize deprecated. So better to use



Answers 19 : of Get height and width of a layout programmatically

you can use coroutines as well, like my code). this one :

CoroutineScope(Dispatchers.Main).launch vendor  {
        val width = thin  view.width()
        val height= little  view.height()
        // do your job lifer  ....

Top rated topics

I wanna call a value from function based widget from another class in the same dart.file into a Text widget

Is there a better way to call a .env file exists check function in cypress?

How to load tflite(learned model) in browser?

Package androidx.core.content does not exist

Adding arrays generated in for loop in Python

How can I call a method that is inside of Component? (I can't pass this method in props)

WooCommerce Email Title / subject line based on shipping method

Replaying change and click events for chained selects

Connecting Flask application and NGINX with Docker "directives not allowed"

Redis HashOperations delete all key

Jquery - FadeIn appears to be pushing down div

Creating a 4 State Mealy Finite State Machine using Verilog [HELP]

Excel VBA Hiding Rows

Convert implicit def to scala 3 given syntax

How to save different plots in the same png file

Android Kotlin ListAdapter add an empty row when add new item to dataset

Function Returning Different Results with Same Inputs

Set WCF Service endpoints at server side web config for https

Scale stateful set with shared volume per az

Choosing a unique answer from Pareto set in multi objective optimization

How to avoid iwebelement list cleared while page refresh

How to properly implement helper functions in a class in python

Stop formset from rendering separate &lt;form&gt; tag - multiple forms one view Django

React Native : Not able to switch to next TextInput on returnKeyType="next" using ref

How to Extract WorkerId from gunicorn workers

Consul logrotation stops when scheduled it to be rotated

Athena federated queries against Postgres JSONB field

Error: pg_config executable not found when install psycopg2 in CentOS 7.9

Flutter web cannot visit url

Append a data frame to include only the words from a list - Python

Why this function doesn't rendering in react

MySql.Data.MySqlClient.MySqlException (0x80004005): Fatal error encountered attempting to read the resultset

How do I make an unweighted, undirected graph with string nodes in Rust?

Complex nested JSON - why is the data undefined

Cannot update with Devcon.exe

Windows neovim vim-plug error: `git` executable not found

SqlMessage: "Unknown column 'c.created' in 'field list'"

Can we replace/change inner html content dynamicaly with java script

When adding two large numbers in SAS, why are the results nonsensical?

How can we send data from one page to other through shared service in angular?

How do I make the still image of the animation leave the screen?

Typescript Deprecation warning

Groupby data to convert from 30 minutes interval to 1 hour

Why the upper limit in breakpoints in material UI for xs is sm?

How do I create an Android App Bundle using Android Studio, command line (first steps from Android instructions don't work, not fully explained)?

Fill column B based on the column value of A

DataTable / DataHelper rows not empty via stored procedure

Flutter find video player 2.2.7 get this error

Apollo Angular Subscription Work in Playground but not in angular app

How to convert large files of dart code to python