parent.getContext within RecyclerView.Adapter's onCreateViewHolder method

依然范特西╮ 提交于 2019-12-10 14:11:46

问题


I have a custom fragment which is attached to my MainActivity. The layout file of the fragment 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>

Within 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 from this method. This ViewGroup is my RecyclerView widget but why gives me parent.getContext a reference to my MainActivity and not to my fragment?


回答1:


Fragments do not really have a context. When working in a fragment and you need a context, normally you need to call getActivity(). In this specific case, the context is passed down from the activity to the fragment to the RecyclerView - remember a view takes a context in it's constructor - and so when you call getContext() on the RecyclerView (the ViewGroup) it returns the activity.



来源:https://stackoverflow.com/questions/30605133/parent-getcontext-within-recyclerview-adapters-oncreateviewholder-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!