"LayoutManager is already attached to a RecyclerView" error
Solution 1:
I had this problem too. My Activity uses Tabs, with three fragments, when I go to third tab, and back to first (or second), this error is thrown.
After searching a lot, I found out that may be the garbage collector, because I was using a strong reference.
Since the constructor LinearLayoutManager uses the activity as the parameter (not the fragment), a Tabs Activity stays active during tabs changes.
Removing the local field in mLinearLayoutManager from the class, and using a weak reference, I could get rid of this problem:
before:
public class MyFragment1 extends Fragment
private LinearLayoutManager linearLayoutManager;
@Override
public void onCreate(Bundle savedInstanceState) {
linearLayoutManager = new LinearLayoutManager(getActivity());
(...)
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
(...)
mRecyclerView.setLayoutManager(linearLayoutManager);
}
}
I changed to:
public class MyFragment1 extends Fragment {
// private LinearLayoutManager linearLayoutManager;
@Override
public void onCreate(Bundle savedInstanceState) {
// linearLayoutManager = new LinearLayoutManager(getActivity());
(...)
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
(...)
mRecyclerView.setLayoutManager(
new LinearLayoutManager(getActivity()));
}
}
Solution 2:
Just need to create a new instance:
RecyclerView recyclerView = new RecyclerView(getContext());
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()))
Solution 3:
I faced this error when providing LayoutManager via Dagger.
The solution is to replace layout manager injection with layout manager javax.inject.Provider injection.
@Inject
lateinit var layoutManager: Provider<RecyclerView.LayoutManager>
...
recyclerView.setLayoutManager(layoutManager.get())