Trevor
Trevor

Reputation: 10993

Determine width and height in Fragment's onCreateView()

In the onCreateView() of my Fragment class I am creating and returning a View whose contents need to be dynamically created based on the actual screen width and height of the Fragment.

It would be most ideal if I were able to determine the width and height within onCreateView(). This is because when the View is constructed within onCreateView(), many child Views are added to it, and how the parent layout View organises those children into columns depending on available width and height (to create a kind of 'fluid' column container).

I tried seeing what LayoutParams are contained in the ViewGroup passed to onCreateView() but the width and height seem to be constants as opposed to specific widths and heights.

Would I be correct in believing that, at this stage in the layout phase (within the Fragment's onCreateView()), there is no width and height available? If that is the case, then what I suspect I need to do is build my container View in two phases: (1) add the children to it initially, and then (2) actually organise those child Views into columns within an override of a method that's called at a point when the width and height are known.

Upvotes: 2

Views: 1896

Answers (1)

Koso
Koso

Reputation: 3199

Yes you are correct. In fragment's onCreateView() width and height are not available yet (both are 0). Doing it exactly like you said in 2 stages is not needed. I suppose you can do it in two ways:

  1. Without custom view: You can use ViewTreeObserver in fragment to determine when width and height are calculated, then calculate size for child views and add them.

  2. With custom view: You can build custom view as you mentioned and in onDraw() you can add child views. In onDraw() method is width and heigh already calculated.

Upvotes: 1

Related Questions