Search code examples
androidscreenviewflipper

Android ViewFlipper measures of undisplayed child


I have a ViewFlipper on my main Activity's View. At onCreate I instante Views which are added to ViewFlipper. After that I set displayed child to first one. And when a button is clicked I switch ViewFlipper's display child to second view. Right after calling viewFlipper.setDisplayedChild(1) I need to do some calculations and instantate some objects which are based on width and height of displayed child.

Main problem here is that at first time (second = 1) child is displayed measurement of view is not done yet. So my width and height are 0. If I go back (setDisplayedChild(0)) and than goes back to second child it is ok (width and height are correct).

I have done some research about that behavior of views and found out that there is a method [onMeasure](http://developer.android.com/reference/android/view/View.html#onMeasure(int, int)) which can be overrided and everything can be done here. OK that how it should be. Actually it is but problem is that onMeasure is called 4 times on each view switch. And my findings was that at first and third call width and height are full screen sized. The second and fourth call are proper width and height. Because I have to instantate new objects at that point it is unwise to do it in onMeasure.

Is there any other, proper way of doing it? Is it possible to force measurement? Do I really need to show view on screen for measurements?

Regards Zmeda


Solution

  • Your init-action (based on width and height of displayed child) should be invoked after measuring of ViewFlipper's children, you can achieve that using method post, e.g.:

        viewFlipper.setDisplayedChild(1);
    
        viewFlipper.post(new Runnable() {
            @Override
            public void run() {
                Log.d("test", "w: " + viewFlipper.getCurrentView().getWidth());// not 0
                //do some calculations and instantate some objects
            }
        });