Bae
Bae

Reputation: 912

When android calculate width and height of views

I create my hierarchy of views by code, and then I do setContentView()in the Activity with my root view like argument.

I need know width and height of one view in runtime but if i do getWidth() or getHeight(), i get 0. If i wait a few seconds i get the correct width or height.

I only want to know in what moment android calculate width / height of views. My code isn't outstanding

Thanks!

Upvotes: 2

Views: 2725

Answers (4)

Alex248
Alex248

Reputation: 427

You can use some View class. add this :

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {

        super(w,h,oldw,oldh);
        if(oldw == 0 && w !=0){
         ...
        // w and h is what you want
    }

Upvotes: 1

Lukas V
Lukas V

Reputation: 423

For clarity, according to this Android documentation

When an Activity receives focus, it will be requested to draw its layout.

...and also measure view dimensions.

Focus receives after onResume and lose it after onPause method.

Upvotes: 0

Carnal
Carnal

Reputation: 22064

This is because in onCreate() the layouts haven't been calculated yet. So you need to add a GlobalLayoutListener to know when layouts has been calculated and placed in screen.

final View view = findViewById(R.id.root);
ViewTreeObserver vto = view.getViewTreeObserver();
            vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    ViewTreeObserver vto = view.getViewTreeObserver();
                    vto.removeGlobalOnLayoutListener(this);
                }
            });

Where root is the root layout (LinearLayout, RelativeLayout i.e). Assign your root layout with the @+id/root.

Upvotes: 3

Simon
Simon

Reputation: 14472

You don't say where you are trying to measure the view but my guess is it's in onCreate() or onResume()>

Try this in your onCreate().

// set a global layout listener which will be called when the layout pass is completed and the view is drawn
     mainLayout.getViewTreeObserver().addOnGlobalLayoutListener(
     new ViewTreeObserver.OnGlobalLayoutListener() {
          public void onGlobalLayout() {
               // measure your views here
          }
     }

Here, mainLayout is a reference to the root view group of the layout.

This will also be called if the layout is resized after it's first drawn (views added in code, orientation changes etc) so you will always get the correct values.

Upvotes: 2

Related Questions