ramzixp ramzixp - 5 months ago 37
Android Question

RecyclerView in Fragment initialize

I'm new with recyclerview, using it with cardview, can somebody tell me how to initialize it?

I see I have to somehow put it in onCreateView, not in ViewCreated, my code:

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {

return inflater.inflate(R.layout.fragment_genres, container, false);


and code of recycler what I was using on Activity but now I want to trigger it in fragments

recyclerView = (RecyclerView) getActivity().findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);


The trace of data:

JSON>get>DataModel>Adapter>Recycler>CardView


When I have it in onCreatedView, LogCat says:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference

Answer

Just like this

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                     @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_genres, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
return v;