faizal
faizal

Reputation: 3565

Get visible position of listview item

I have a custom cursor adapter to populate a list view in my fragment.

I want to set the visibility of certain elements within the list view items, depending on whether the item is the first visible one in the list or not. Is it possible to get that info in the bindView() method of the Cursor adapter?

Upvotes: 1

Views: 1605

Answers (1)

Simas
Simas

Reputation: 44118

Adapter's purpose plan:

  1. Create views
  2. Attaching data to them
  3. Return the view for the ListView to use.

Conclusion: Adapter doesn't know where the view it's creating will be shown.

However, the ListView does know about this and it's probably the only way you can get this working.

Example code to get you started:

listView.setOnScrollListener(new AbsListView.OnScrollListener() {
    int previousFirst = -1;
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (previousFirst != firstVisibleItem) {
            previousFirst = firstVisibleItem;
            TextView textView = (TextView) view.findViewById(R.id.title);
            if (textView != null) textView.setText("First: " + firstVisibleItem);
        }
    }
});

Problems with this code:

  • Once the first item changes, you need to set it's text back to the previous one.
  • Same goes with the view hierarchy. If you change how this view looks, after it's not the first one anymore you need to change it back.
  • ListView doesn't scroll upon creation. So the first item will not have the text changed until you scroll manually.

ListView doesn't include the options to customize the first visible item internally, that's why you have to use all these dirty hacks. However, it is possible :). I leave you to overcome these problems yourself.

Good luck!

Upvotes: 3

Related Questions