Is there a good reason for a ListView header taking up a position?

↘锁芯ラ 提交于 2019-12-05 21:27:58

问题


I've just added a header to my ListView and I have to change a bunch of code because the header essentially becomes position 0 (Meaning the Cursor indices of my CursorAdapter do not line up with the indicies of the list. They are off by 1 now). Why? This seems a bit silly to me.

The only reason I can come up with is that a developer may want to access the header. Fine. Provide something like getListView().getHeader().


回答1:


For some reason the position (from the onItemClick) is tied up with the number of items in the ListView (not the adapter), including headers and footers. When you set an OnItemClickListener you should retrieve the clicked item by calling listView.getItemAtPosition(position) instead of adapter.getItem(position).

In fact, you should always use the getItemAtPosition, because that way not matter if your ListView has headers and footers, and if you add new headers you won't need to change your code.

And if you don't want your header to be selectable, you should add it in this way: listView.addHeaderView(headerView, null, false).




回答2:


I believe a ListView is nothing more than a list of View elements. If you add a header (or a footer for that matter, it shouldn't make any difference) to your ListView, that element is basically no different from any of the other elements that gets added automatically through the ListAdapter. The only minor difference being that the header (and footer) element will be fixed and stay unaffected by what the ListAdapter does with the list - they are still nothing but ordinary elements though.



来源:https://stackoverflow.com/questions/4027997/is-there-a-good-reason-for-a-listview-header-taking-up-a-position

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