Search code examples
androidandroid-listviewandroid-cursoradapter

Change text(title) according item in CursorAdapter ListView


I have a ListView in an Activity and a TextView above. How can I change TextView text according with the items displayed in ListView?

The ListView Adapter is a CursorAdapter.

Example: In the table fields, I can access the month. If the month of the records displayed in Top of the ListView is January, for example, the TextView should show "January", but sliding the ListView, the top item is February, the TextView changes to "February"

Thanks!


Solution

  • Use an OnScrollListener to tell you when the top item might have changed.

    private final OnScrollListener mOnScrollListener = new OnScrollListener() {
    
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }
    
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    
           ListAdapter adapter = mListView.getAdapter();
           if (adapter == null || visibleItemCount == 0)
               return;
    
           Object item = adapter.getItem(firstVisibleItem);
           // you would cast item to the type of your list item model
           // determine which month the list item applies to
           // set the month in the title text view
    
        }
    
    };