Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between getActivity() and view in Fragment

What is the difference between

getActivity().findViewById(...)

and

View view = inflater.inflate(R.layout.fragment_fragment_v, null);
view.findViewById(...)

in Fragment (when converting Activity to Fragment)?

like image 898
Amy Avatar asked Dec 29 '25 13:12

Amy


1 Answers

The difference is that with getActivty.findViewById(...) you are finding views in the scope of activity (activity's layout). With iflater.inflate(R.layout.fragment_fragment_v, null); view.findViewById(...) you are inflating the layout of your fragment and then finding view's in that layout.

But since your fragment is attached to the activity, you will find the view bothways, but I suggest you are finding view's for your fragment in your fragment's scope since there may be several fragments that have common layouts meaning there may be several view's associated with the same ID and that makes the getActivity().findBiewById(...) method unreliable

like image 134
Bojan Kseneman Avatar answered Jan 01 '26 22:01

Bojan Kseneman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!