1

In my app, I need to set the width of a view based on the width of another view. However, Activity's onCreate() method does not seem to be a good place to do so. The view's width via getWidth() returns 0. Other methods onStart() and onResume() also behave similarly.

I am wondering if there is any method on an Activity that is called after a view has been initialized? Or, is there is another way I can achieve my objective.

Zong
  • 6,160
  • 5
  • 32
  • 46
Peter
  • 11,260
  • 14
  • 78
  • 155
  • This should be useful http://stackoverflow.com/questions/4393612/when-can-i-first-measure-a-view – MP23 Dec 18 '13 at 20:46

2 Answers2

3

Try onGlobalLayoutListener. Get the instance of your main root view, and then just use addOnGlobalLayoutListener() method.

You will receive a callback when your views are already created and measured on Screen:

http://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html

noni
  • 2,927
  • 19
  • 18
0

Declare onGlobalLayoutListener in onCreate method:

View firstView = (View) findViewById(R.id.firstView);
View secondView = (View) findViewById(R.id.secondView);

firstView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {

    // Ensure you call it only once :
        firstView.getViewTreeObserver().removeGlobalOnLayoutListener(this);

        int width = firstView.getWidth();
        int height = firstView.getHeight();

    // set dimensions of another view with that dimensions

        secondView.setWidth(width);
        secondView.setHeight(height);
    }
});  
ramaral
  • 6,149
  • 4
  • 34
  • 57