如何在Fragment中设置适配器
我有一个 Fragment
,其 onCreateView()
回调返回自定义 View
。该视图包含一个我想在其上设置适配器的 GridView。在我改用 Fragments 之前,我只需通过 Id 找到 GridView,然后设置适配器。由于我目前不明白的原因,当我尝试在 FragmentsActivity
中通过 Id 查找时,GridView
为空。
因此,我想在 fragment
本身中设置适配器。我假设我需要在 onActivityCreated
中执行此操作,但我不知道如何在 GridView
上设置 adapter
包含在 onCreateView 返回的 View 中。换句话说,如何获取 onCreateView
返回的 View 并在其上设置 Adapter
?
编辑 - 我刚刚意识到,我可能可以在 onActivityCreated 中找到 GridView 并在那里设置适配器,不是吗?
I've got a Fragment
whose onCreateView()
callback returns a custom View
. The View contains a GridView that I'd like to set an adapter on. Before I switched to using Fragments, I would simply find the GridView
by Id and then set the adapter
. For reasons I don't currently understand, the GridView
is null when I try finding it by Id in my FragmentsActivity
.
So, I'd like to set the adapter in the fragment
itself. I'm assuming I need to do this in onActivityCreated
, but I don't know how I'll set the adapter
on the GridView
that's contained within the View being returned by onCreateView. In other words, how do I grab hold of that View that's returned by onCreateView
to set the Adapter
on it?
EDIT - I just realized, I could probably just find the GridView
in onActivityCreated
and set the adapter
there, no?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在
onCreateView()
的片段中创建了GridView
。只需将其保留在片段的数据成员中即可。You created the
GridView
in the fragment inonCreateView()
. Just hold onto it in a data member of the fragment.我知道这个答案来得有点晚了(而且我对 Android 还很陌生)。但是,如果在
onActivityCreated
内部使用getView()
,而不是通过 ID 查找它呢?I know this answer comes a little late (and also I am quite new to Android). But what about using
getView()
inside ofonActivityCreated
, instead of finding it by ID?