Implement a RecyclerView in a Fragment
23,905
Use this
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_city_list, container, false)
// Replace 'android.R.id.list' with the 'id' of your RecyclerView
mRecyclerView = (RecyclerView) view.findViewById(android.R.id.list);
mLayoutManager = new LinearLayoutManager(this.getActivity());
Log.d("debugMode", "The application stopped after this");
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecyclerAdapter(getNames());
mRecyclerView.setAdapter(mAdapter);
return view;
}
You should call the setLayoutManager
& setAdapter
methods (respectively) on the Recyclerview
.
Plus,
mRecyclerView = (RecyclerView) view.findViewById(android.R.id.list);
you should not use android.R.id.list
, as you're not using a ListFragment
. Replace it with the id
of you Recyclerview
(as in your XML layout).
Author by
user3432681
Updated on January 14, 2020Comments
-
user3432681 over 4 years
I trying to create a ListView in a Fragment within a ViewPager in a AppCompatActivity. In the AppCompatActivity are all view elements are wrappend in a CoordinatorLayout. Because I used the CoordinatorLayout. I have to use a RecylerView I am trying to follow the training from developer.android.com, but my application stopped after my log. This is my code in myFragment where the applications stopped.
import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; //... @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_city_list, container, false) mRecyclerView = (RecyclerView) view.findViewById(android.R.id.list); mLayoutManager = new LinearLayoutManager(this.getActivity()); Log.d("debugMode", "The application stopped after this"); mRecyclerView.setLayoutManager(mLayoutManager); mAdapter = new RecyclerAdapter(getNames()); mRecyclerView.setAdapter(mAdapter); return view; } //...
-
user3432681 over 8 yearsWoww Thank you! it was very late i didn't see that R.id.list did not reference to my list! I was stuck for hours!
-
TheCoderGuy over 5 yearsI have an question where does the getNames come from ?
-
Mohammed Aouf Zouag over 5 years
getNames()
is a method that returns the list of data to populate theRecyclerView