Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get width and height of components in Fragment view

Tags:

android

I need access to already evaluated width and height of all component in Fragment view. So I need some notification which tell me, that view of fragment layouting phase is already done.

In activity I can use onWindowFocusChanged(boolean hasFocus) life cycle method, but fragment doesn't have this method.

Only way that i found is use getView().addOnLayoutChangeListener(). But it call multiple times and only last call is usefull for me.

Exist any better way how to call some after layout is done in fragment's view?

like image 662
ATom Avatar asked May 02 '12 07:05

ATom


1 Answers

You can actually trigger a layout pass manually - you just need to call View.measure(int,int) with the appropriate MeasureSpecs. For example if the Fragment is to be attached to a parent view parentView, and you want it to have the same size, you'd do this:

View fragmentView = fragment.getView();
fragmentView.measure(MeasureSpec.makeMeasureSpec(parentView.getMeasuredWidth(),
                                                 MeasureSpec.EXACTLY),
                     MeasureSpec.makeMeasureSpec(parentView.getMeasuredHeight(),
                                                 MeasureSpec.EXACTLY));

More about how the measure/layout passes work: http://developer.android.com/reference/android/view/View.html#Layout

like image 128
Marcus Forsell Stahre Avatar answered Oct 07 '22 03:10

Marcus Forsell Stahre