RecyclerView.Adapter的onCreateViewHolder方法中的parent.getContext [英] parent.getContext within RecyclerView.Adapter's onCreateViewHolder method

查看:541
本文介绍了RecyclerView.Adapter的onCreateViewHolder方法中的parent.getContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义片段,该片段附加在MainActivity上。片段的布局文件包含recyclerview小部件。

I have a custom fragment which is attached to my MainActivity. The layout file of the fragment contains the recyclerview widget.

fragment_main.xml:

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>

在我的RecyclerView.Adapter中,onCreateViewHolder方法如下:

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

我的问题是关于使用此方法的Viewgroup父级。这个ViewGroup是我的RecyclerView小部件,但是为什么给我parent.getContext引用我的MainActivity而不是我的片段?

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?

推荐答案

Fragments确实没有上下文。在片段中工作且需要上下文时,通常需要调用 getActivity()。在此特定情况下,上下文从活动传递到片段,再传递到RecyclerView-记住视图在其构造函数中包含上下文-因此当您调用 getContext()在RecyclerView(ViewGroup)上返回活动。

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.

这篇关于RecyclerView.Adapter的onCreateViewHolder方法中的parent.getContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆