What is the difference between getView () and getActivity ()?

What is the difference between getView() and getActivity() ?

I used both methods, but I don’t understand the main difference, even the usage methodology is also the same in android:

 ListView deliverItemList = (ListView) getView().findViewById(R.id.load_item_list); ListView deliverItemList = (ListView) getActivity().findViewById(R.id.load_item_list); 

I suggested that getView() could getView() a NullPointerException , share its knowledge with me and which method is recommended?

+6
source share
2 answers

getActivity() returns Activity hosting Fragment , and getView() returns the view that you fanned and returned using onCreateView . The latter returns != null only after onCreateView returns

+7
source

From android docs:

getActivity () returns the action that this fragment is currently associated with, and getView () returns the root view for (the one that returns onCreateView (LayoutInflater, ViewGroup, Bundle)), if provided.

So, in your case, the following line of code:

 getView().findViewById(R.id.load_item_list); 

you are looking for representation in your snippet, but using the following line of code:

 getActivity().findViewById(R.id.load_item_list); 

You are looking for an idea in your activity in which your fragment is posted.

About your question about which one to use, it depends. If you are trying to inflate a fragment, you need to inflate your xml in onCreateView, and using this inflated view, you look for your views as follows:

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.your_layout, container, false); ListView lv = (ListView)v.findViewById(R.id.view_id); } 
+6
source

All Articles