Implement RecyclerView in fragment

I am trying to create a ListView in a fragment in a ViewPager in AppCompatActivity. In AppCompatActivity, all view elements are wrappend in CoordinatorLayout. Because I used the Layout coordinator. I have to use RecylerView. I try to follow developer.android.com , but my application stopped after my magazine. 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; } //... 
+5
source share
2 answers

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; } 

On Recyclerview you should call the setLayoutManager and setAdapter ( respectively ) methods.

Besides,

mRecyclerView = (RecyclerView) view.findViewById(android.R.id.list);

you should not use android.R.id.list since you are not using ListFragment . Replace its id from you with Recyclerview (as in your XML layout).

+10
source

Have you set android.R.id.list as the recyclerview id? otherwise, you must set the id for recyclerview in the XML file, for example:

 android:id="@+id/recyclerview" 

and change this line

 mRecyclerView = (RecyclerView) view.findViewById(android.R.id.list); 

to

 mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview); 
-1
source

Source: https://habr.com/ru/post/1238203/


All Articles