When does android's ListActivity class call setContentView()?

本小妞迷上赌 提交于 2019-12-24 07:26:26

问题


I'm trying to use the requestWindowFeature() function to set a custom title view on a list activity. The method works fine with a view that only subclasses Activity, but whenever I try the same method with a ListActivity subclass, it errors, giving me a NullPointerException when I try to programmatically modify the title view.

I believe the problem pertains to the fact that requestWindowFeature() needs to be called before setContentView(). Because ListActivity takes care of setting the content view for you, I don't know when that is being called. Does anyone have any suggestions? Thanks for the help.


回答1:


setContentView is called whenever you interact with the List, for example calling getList() or setAdapter() on listactivity. See the source of listactivity




回答2:


ListActivity doesn't take care of calling setContentView for you: you still need to do it yourself. Your content view has to have an appropriately-named ListView but you still need to call setContentView yourself. Just call requestWindowFeature right after the super.onCreate call in onCreate and then call setContentView after that and you should be golden.

EDIT: my mistake, you are quite right (I didn't know that: I've always just called setContentView with a custom layout).

It appears from here that there is no way to slip a requestWindowFeature call before the setContentView call in ListActivity: it ALWAYS calls setContentView immediately after the super.onCreate call. You can try calling requestWindowFeature before you call super.onCreate but I suspect that won't work any better.

I don't think you will be able to use the default ListActivity for this: you'll probably need to use a regular Activity and manually do the ListView bindings.




回答3:


The solution to my problem, for any googlers, was to copy the source of the ListActivity class, and also the layout_content.xml file into my own app's package, and subclass from this instead of Android's ListActivity class. I then added an onCreate() method to this class where I set request the window feature(s) and then call the setContentView() method. Hack? Probably. Works? Yes :)




回答4:


Sometimes, requestWindowFeature() gives a NullPointerException if it's called after the super.onCreate(bundle); call. Another reason is if you have called setContentView first as well.

super.onCreate(bundle); and setContentView must be called after all requestWindowFeature() calls are made.



来源:https://stackoverflow.com/questions/6903487/when-does-androids-listactivity-class-call-setcontentview

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