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

左心房为你撑大大i 提交于 2019-12-01 17:50:20

getActivity() returns the Activity hosting the Fragment, while getView() returns the view you inflated and returned by onCreateView. The latter returns a value != null only after onCreateView returns

From android docs:

getActivity() returns the Activity this fragment is currently associated with, and getView() returns the root view for the fragment's layout (the one returned by onCreateView(LayoutInflater, ViewGroup, Bundle)), if provided.

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

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

you are searching for the view in your fragment, but using the following line of code:

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

you are searching for the view in your activity hosting your fragment.

About your question of which one to use, it depends. If you are trying to inflate fragment, you need to inflate your xml in onCreateView, and using that inflated view you search for your views like this:

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!