getLastVisiblePosition returning -1

2019-01-14 22:51发布

问题:

I'm having a problem with my ListView (using CursorAdapter). When I call getListView().getLastVisiblePosition() I am receiving -1. This is a problem since my list is populated with items. Additionally, getListView().getFirstVisiblePosition() always returns 0, no matter where I am scrolled on the list. Any ideas?

It has something to do with startManagingCursor

    @Override
    public void changeCursor(Cursor cursor) {
        super.changeCursor(cursor);
        MyActivity.this.mCursor = cursor;
        //startManagingCursor(MyActivity.this.mCursor);
    }

If I comment out startManagingCursor, everything works fine. I've also tried adding stopManagingCursor() before changing the Cursor and still have the same problem.

回答1:

This is because the moment you call getListView().getLastVisiblePosition() the listview is not rendered. You can add the call to the view's message queue like this:

listview.post(new Runnable() {
    public void run() {
        listview.getLastVisiblePosition();
    }
});


回答2:

Even I faced the same problem. The thing is that, getLastVisiblePosition() works only when you are in the first element of your listview and for the rest you will get null being returned. So what I did is that, I made a small calculation to find out the exact view position which I have mentioned below,

int  LastPos=(mylist.getLastVisiblePosition()-mylist.getFirstVisiblePosition());

This returns the exact last position without a doubt.



回答3:

My guess is that your getItem(int position) and getItemId(int position) methods aren't defined correctly in your adapter.