问题描述
我有一些麻烦设置我的自定义的头在我的列表中。
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,但被调用每一个我的片段回来从backstack时间,因为我也把我的适配器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加入它,但我不能投从膨胀到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.setListAdapter()
在 ListFragment.onCreate()
。请确保您有一个字段变量,可以保存头来看,也许这样的:
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);
这篇关于最好的地方,addHeaderView在ListFragment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!