ListView addHeaderView causes position to increase by one?

Solution 1:

I just came across this problem and the best way seems to use the ListView.getItemAtPosition(position) instead of ListAdapter.getItem(position) as the ListView version accounts for the headers, ie:-

Do this instead:

myListView.getItemAtPosition(position)

Solution 2:

If you don't care about the click to the header, subtract the number of header views from the position to get the position for your adapter:

        listView.addHeaderView(inflater.inflate(
                R.layout.my_hdr_layout, null), null, false);
        listView.setAdapter(m_adapter);
        listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            position -= listView.getHeaderViewsCount();
            final MyObject object = m_adapter.getItem(position);

        }
    });

Solution 3:

If you add a header to a ListView that becomes the first item in the list. You could compensate for this by overriding the getCount() to return one item less, but ensure you handle the getItem(), getItemId() and so on as the header would be the item in position 0.