Parent.getContext in RecyclerView.Adapter onCreateViewHolder method

I have a custom snippet that is bound to my MainActivity. The fragment layout file contains the recyclerview widget.

fragment_main.xml:

<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="vertical"/> </FrameLayout> 

Inside my RecyclerView.Adapter, the onCreateViewHolder method looks like this:

 @Override public MyAdapter.MyHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout .list_item, parent, false); return new MyHolder(view); } 

My question is about the Viewgroup parent of this method. This ViewGroup is my RecyclerView widget, but why does it give me parent.getContext a link to my MainActivity, and not to my fragment?

+5
source share
1 answer

Fragments do not really have context. When you work in a fragment and you need context, usually you need to call getActivity() . In this particular case, the context is passed from the operation to the fragment in the RecyclerView - remember that the view takes the context in it - and therefore, when you call getContext() in the RecyclerView (ViewGroup), it returns the action.

+11
source

All Articles