在 ListFragment 中添加HeaderView 的最佳位置 [英] Best place to addHeaderView in ListFragment

查看:19
本文介绍了在 ListFragment 中添加HeaderView 的最佳位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在列表中设置自定义标题时遇到了一些问题.

I'm having some trouble setting up my custom header in my list.

我正在使用自定义适配器创建 ListFragment.我的列表工作正常,但我试图找出在片段的生命周期中附加标题的位置.

I'm creating a ListFragment with a custom adapter. I have the list working fine, but I'm trying to figure out where in the lifecycle of a Fragment to attach the header.

我知道必须在设置适配器之前添加标题.

I know the header has to be added before you set your adapter.

我尝试在 onActivityCreated 中添加我的标头,但是每次我的 Fragment 从后台堆栈返回时都会调用它,并且由于我还在 onActivityCreated 中设置了我的适配器,所以它失败了.

I tried adding my header in onActivityCreated, but that gets called every time my Fragment comes back from the backstack, and since I also set my adapter in onActivityCreated, it fails.

我尝试在 onCreate 中添加它,但视图层次结构在生命周期的那个阶段不可用.

I tried adding it in onCreate, but the view hierarchy isn't available at that stage of the lifecycle.

我尝试将它添加到 onCreateView 中,但我无法将从 inflate 返回的视图转换为 ListView.所以我无法将我的标题添加到香草视图中.

I tried adding it in onCreateView, but I couldn't cast the view returned from inflate to a ListView. So I couldn't add my header to a vanilla View.

有什么想法吗?

推荐答案

我不知道你是否解决了你的问题,但这里有一个对我有用的解决方案:

I don't know if you have solved your problem but here is a solution that worked for me:

不要在 ListFragment.onCreate() 中调用 ListFragment.setListAdapter().确保你有一个可以保存标题视图的字段变量,可能像:

Do not call ListFragment.setListAdapter() in your ListFragment.onCreate(). Make sure you have a field variable that can hold the header view, maybe like:

View mheaderView;

然后在您的 ListFragment.onCreateView() 中,膨胀标题视图并将其分配给您的变量,如下所示:

Then in your ListFragment.onCreateView(), inflate the header View and assign it to your variable like so:

View list_root = inflater.inflate(R.layout.fragment_list, null);
// Get the list header - to be added later in the lifecycle
// during onActivityCreated()
mheaderView = inflater.inflate(R.layout.list_header, null);
return list_root;

最后,在您的 ListFragment.onActivityCreated() 中,您现在可以调用 ListFragment.getListView().addHeaderView().基本上是这样的:

Finally, in your ListFragment.onActivityCreated() you can now call ListFragment.getListView().addHeaderView(). Basically something like so:

super.onActivityCreated(savedInstanceState);
if (mheaderView != null)  this.getListView().addHeaderView(headerView);
// Don't forget to now call setListAdapter()
this.setListAdapter(listAdapter);

这篇关于在 ListFragment 中添加HeaderView 的最佳位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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