hewa jalal
hewa jalal

Reputation: 963

Which one of these is the best way to access android fragment views?

How are these methods different from each other when trying to get the view?

First:

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_a, container, false);
    listView = view.findViewById(R.id.listview);
    return view;
}

Second:

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
     listView = getActivity().findViewById(R.id.listview);  }

* some say this is used to get activity views but i used it for getting fragment views(which didn't existed in the activity) and it worked fine.

Third:

 @Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    listView = getView().findViewById(R.id.listview);
}

Upvotes: 1

Views: 87

Answers (1)

Climbatize
Climbatize

Reputation: 1123

Three methods are good. In the onCreateView you create the view (!), it's the really first time you can use what you inflated. Then onViewCreated is called with the view you returned in the onCreateView, You can directly use the view given as parameter, it is the same the getView() provides. My advice is to initialise your UI variables here

For onActivityCreated, it is the best place to modify your UI elements. It is called when fragment creation is complete and when fragment is re-attached. There you can use the variables you initialised before, without having to get the activity just for that purpose.

Android Activity and Fragment lifecycle

Upvotes: 1

Related Questions