2

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!

1

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You were still typing as I posted :)
Haha yeah you posted the answer a couple of seconds before :P
2

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.

1 Comment

Thanks for learning me something new. view.post doesn't seem to work on all devices. Another discussion on the same subject here: stackoverflow.com/a/13944263/969325
1

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 } 

1 Comment

I put the createScaledBitmap method to there and it works perfect. Also the error that says Avoid object allocations during draw/layout operations (preallocate and reuse instead) is disappeared. Thanks a lot..
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.