In my fragment's onCreateView
method, I used to store the inflated layout in a variable and then pass the latter to my other functions that called findViewById
on this inflated View
.
Now, I prefer to just return the inflated layout (I don't store it). Thus, I don't pass any value to my other functions that call findViewById
. But they still call findViewById
; how? Simply by calling Objects.requireNonNull(getActivity()).findViewById
.
Talking about fragments, is it equivalent? For example:
In terms of RAM or CPU consumption
Looking through the fragment's view directly will be faster because you'll search through a shallower hierarchy. This shouldn't be concerning you, it will be insignificant in terms of performance.
In term of behavior (is there any risk with the second way to do it?)
You shouldn't use getActivity().findViewById(). A fragment should be independent and manage its view directly and not through an indirection(like getActivity()). You also risk introducing subtle bugs due to the way findViewById() works(meaning it returns the first view with the specified id that it found).
Imagine you have the same fragment used as the pages of a ViewPager. Using getActivity().findViewById() means you'll only reference the views from the first instance of the fragment referenced by the ViewPager(and not the other pages). Another example would be when you have a View with an id in the activity and a view with the same id in the Fragment(at a deeper level) . Using getActivity().findViewById() will reference the activity View and not the View found in the fragment.