Class ListView

All Implemented Interfaces:
Drawable.Callback, ViewManager, ViewParent, Filter.FilterListener
Direct Known Subclasses:
DropDownListView, ExpandableListView

public class ListView extends AbsListView

Displays a vertically-scrollable collection of views, where each view is positioned immediately below the previous view in the list. For a more modern, flexible, and performant approach to displaying lists, use

invalid reference
RecyclerView
.

A list view is an adapter view that does not know the details, such as type and contents, of the views it contains. Instead list view requests views on demand from a ListAdapter as needed, such as to display new views as the user scrolls up or down.

In order to display items in the list, call setAdapter(ListAdapter adapter) to associate an adapter with the list. For a simple example, see the discussion of filling an adapter view with text in the Layouts guide.

To display a more custom view for each item in your dataset, implement a ListAdapter. For example, extend BaseAdapter and create and configure the view for each data item in getView(...):

private class MyAdapter extends BaseAdapter {

      // override other abstract methods here

      @Override
      public View getView(int position, View convertView, ViewGroup container) {
          if (convertView == null) {
              convertView = getLayoutInflater().inflate(R.layout.list_item, container, false);
          }

          ((TextView) convertView.findViewById(android.R.id.text1))
                  .setText(getItem(position));
          return convertView;
      }
  }

ListView attempts to reuse view objects in order to improve performance and avoid a lag in response to user scrolls. To take advantage of this feature, check if the convertView provided to getView(...) is null before creating or inflating a new view object. See Making ListView Scrolling Smooth for more ways to ensure a smooth user experience.

To specify an action when a user clicks or taps on a single list item, see Handling click events.

To learn how to populate a list view with a CursorAdapter, see the discussion of filling an adapter view with text in the Layouts guide. See Using a Loader to learn how to avoid blocking the main thread when using a cursor.

  • Constructor Details

    • ListView

      public ListView(Context context)
  • Method Details

    • getMaxScrollAmount

      public int getMaxScrollAmount()
      Returns:
      The maximum amount a list view will scroll in response to an arrow event.
    • addHeaderView

      public void addHeaderView(@NonNull View v, Object data, boolean isSelectable)
      Add a fixed view to appear at the top of the list. If this method is called more than once, the views will appear in the order they were added. Views added using this call can take focus if they want.

      If the ListView's adapter does not extend HeaderViewListAdapter, it will be wrapped with a supporting instance of WrapperListAdapter.

      Parameters:
      v - The view to add.
      data - Data to associate with this view
      isSelectable - whether the item is selectable
    • addHeaderView

      public void addHeaderView(@NonNull View v)
      Add a fixed view to appear at the top of the list. If this method is called more than once, the views will appear in the order they were added. Views added using this call can take focus if they want.

      If the ListView's adapter does not extend HeaderViewListAdapter, it will be wrapped with a supporting instance of WrapperListAdapter.

      Parameters:
      v - The view to add.
    • getHeaderViewsCount

      public int getHeaderViewsCount()
    • removeHeaderView

      public boolean removeHeaderView(@NonNull View v)
      Removes a previously-added header view.
      Parameters:
      v - The view to remove
      Returns:
      true if the view was removed, false if the view was not a header view
    • addFooterView

      public void addFooterView(@NonNull View v, Object data, boolean isSelectable)
      Add a fixed view to appear at the bottom of the list. If this method is called more than once, the views will appear in the order they were added. Views added using this call can take focus if they want.

      If the ListView's adapter does not extend HeaderViewListAdapter, it will be wrapped with a supporting instance of WrapperListAdapter.

      Parameters:
      v - The view to add.
      data - Data to associate with this view
      isSelectable - true if the footer view can be selected
    • addFooterView

      public void addFooterView(@NonNull View v)
      Add a fixed view to appear at the bottom of the list. If this method is called more than once, the views will appear in the order they were added. Views added using this call can take focus if they want.

      If the ListView's adapter does not extend HeaderViewListAdapter, it will be wrapped with a supporting instance of WrapperListAdapter.

      Parameters:
      v - The view to add.
    • getFooterViewsCount

      public int getFooterViewsCount()
    • removeFooterView

      public boolean removeFooterView(@NonNull View v)
      Removes a previously-added footer view.
      Parameters:
      v - The view to remove
      Returns:
      true if the view was removed, false if the view was not a footer view
    • getAdapter

      public ListAdapter getAdapter()
      Returns the adapter currently in use in this ListView. The returned adapter might not be the same adapter passed to setAdapter(ListAdapter) but might be a WrapperListAdapter.
      Specified by:
      getAdapter in class AdapterView<ListAdapter>
      Returns:
      The adapter currently used to display data in this ListView.
      See Also:
    • setAdapter

      public void setAdapter(@Nullable ListAdapter adapter)
      Sets the data behind this ListView.

      The adapter passed to this method may be wrapped by a WrapperListAdapter, depending on the ListView features currently in use. For instance, adding headers and/or footers will cause the adapter to be wrapped.

      Overrides:
      setAdapter in class AbsListView
      Parameters:
      adapter - The ListAdapter which is responsible for maintaining the data backing this list and for producing a view to represent an item in that data set.
      See Also:
    • requestChildRectangleOnScreen

      public boolean requestChildRectangleOnScreen(@NonNull View child, @NonNull Rect rect, boolean immediate)
      Description copied from interface: ViewParent
      Called when a child of this group wants a particular rectangle to be positioned onto the screen. ViewGroups overriding this can trust that:
      • child will be a direct child of this group
      • rectangle will be in the child's content coordinates

      ViewGroups overriding this should uphold the contract:

      • nothing will change if the rectangle is already visible
      • the view port will be scrolled only just enough to make the rectangle visible
      Specified by:
      requestChildRectangleOnScreen in interface ViewParent
      Overrides:
      requestChildRectangleOnScreen in class ViewGroup
      Parameters:
      child - The direct child making the request.
      rect - The rectangle in the child's coordinates the child wishes to be on the screen.
      immediate - True to forbid animated or delayed scrolling, false otherwise
      Returns:
      Whether the group scrolled to handle the operation
    • smoothScrollToPosition

      public void smoothScrollToPosition(int position)
      Smoothly scroll to the specified adapter position. The view will scroll such that the indicated position is displayed.
      Overrides:
      smoothScrollToPosition in class AbsListView
      Parameters:
      position - Scroll to this adapter position.
    • smoothScrollByOffset

      public void smoothScrollByOffset(int offset)
      Smoothly scroll to the specified adapter position offset. The view will scroll such that the indicated position is displayed.
      Parameters:
      offset - The amount to offset from the adapter position to scroll to.
    • onDetachedFromWindow

      protected void onDetachedFromWindow()
      Description copied from class: View
      This is called when the view is detached from a window. At this point it no longer has a surface for drawing.
      Overrides:
      onDetachedFromWindow in class AbsListView
      See Also:
    • onSizeChanged

      protected void onSizeChanged(int w, int h, int oldw, int oldh)
      Description copied from class: View
      Called when width or height changed
      Overrides:
      onSizeChanged in class AbsListView
      Parameters:
      w - new width
      h - new height
      oldw - previous width
      oldh - previous height
    • onMeasure

      protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
      Description copied from class: View
      Measure the view and its content to determine the measured width and the measured height. This method is invoked by View.measure(int, int) and should be overridden by subclasses to provide accurate and efficient measurement of their contents.

      CONTRACT: When overriding this method, you must call View.setMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger an IllegalStateException, thrown by View.measure(int, int). Calling super.onMeasure() is a valid use.

      The base class implementation of measure defaults to the background size, unless a larger size is allowed by the MeasureSpec. Subclasses should override the base one to provide better measurements of their content.

      Overrides:
      onMeasure in class AbsListView
      Parameters:
      widthMeasureSpec - width measure specification imposed by the parent MeasureSpec
      heightMeasureSpec - height measure specification imposed by the parent MeasureSpec
    • recycleOnMeasure

      @Internal protected boolean recycleOnMeasure()
      Returns:
      True to recycle the views used to measure this ListView in UNSPECIFIED/AT_MOST modes, false otherwise.
    • layoutChildren

      protected void layoutChildren()
      Description copied from class: AbsListView
      Subclasses must override this method to layout their children.
      Overrides:
      layoutChildren in class AbsListView
    • setSelection

      public void setSelection(int position)
      Sets the currently selected item. If in touch mode, the item will not be selected but it will still be positioned appropriately. If the specified selection position is less than 0, then the item at position 0 will be selected.
      Specified by:
      setSelection in class AdapterView<ListAdapter>
      Parameters:
      position - Index (starting at 0) of the data item to be selected.
    • setSelectionAfterHeaderView

      public void setSelectionAfterHeaderView()
      setSelectionAfterHeaderView set the selection to be the first list item after the header views.
    • dispatchKeyEvent

      public boolean dispatchKeyEvent(@NonNull KeyEvent event)
      Description copied from class: View
      Dispatch a key event to the next view on the focus path. This path runs from the top of the view tree down to the currently focused view. If this view has focus, it will dispatch to itself. Otherwise it will dispatch the next node down the focus path. This method also fires any key listeners.
      Overrides:
      dispatchKeyEvent in class ViewGroup
      Parameters:
      event - The key event to be dispatched.
      Returns:
      True if the event was handled, false otherwise.
    • onKeyDown

      public boolean onKeyDown(int keyCode, @NonNull KeyEvent event)
      Description copied from class: View
      Default implementation: perform press of the view when KeyEvent.KEY_ENTER, KeyEvent.KEY_KP_ENTER or KeyEvent.KEY_SPACE is released, if the view is enabled and clickable.
      Overrides:
      onKeyDown in class AbsListView
      Parameters:
      keyCode - a key code that represents the button pressed, from KeyEvent
      event - the KeyEvent object that defines the button action
    • onKeyUp

      public boolean onKeyUp(int keyCode, @NonNull KeyEvent event)
      Description copied from class: View
      Default implementation: perform clicking of the view when KeyEvent.KEY_ENTER, KeyEvent.KEY_KP_ENTER or KeyEvent.KEY_SPACE is released.
      Overrides:
      onKeyUp in class AbsListView
      Parameters:
      keyCode - A key code that represents the button pressed, from KeyEvent.
      event - The KeyEvent object that defines the button action.
    • setItemsCanFocus

      public void setItemsCanFocus(boolean itemsCanFocus)
      Indicates that the views created by the ListAdapter can contain focusable items.
      Parameters:
      itemsCanFocus - true if items can get focus, false otherwise
    • getItemsCanFocus

      public boolean getItemsCanFocus()
      Returns:
      Whether the views created by the ListAdapter can contain focusable items.
    • dispatchDraw

      protected void dispatchDraw(@NonNull Canvas canvas)
      Description copied from class: View
      Draw the child views.
      Overrides:
      dispatchDraw in class AbsListView
      Parameters:
      canvas - the canvas to draw content
    • getDivider

      @Nullable public Drawable getDivider()
      Returns the drawable that will be drawn between each item in the list.
      Returns:
      the current drawable drawn between list elements
    • setDivider

      public void setDivider(@Nullable Drawable divider)
      Sets the drawable that will be drawn between each item in the list.

      Note: If the drawable does not have an intrinsic height, you should also call setDividerHeight(int).

      Parameters:
      divider - the drawable to use
    • getDividerHeight

      public int getDividerHeight()
      Returns:
      Returns the height of the divider that will be drawn between each item in the list.
    • setDividerHeight

      public void setDividerHeight(int height)
      Sets the height of the divider that will be drawn between each item in the list. Calling this will override the intrinsic height as set by setDivider(Drawable)
      Parameters:
      height - The new height of the divider in pixels.
    • setHeaderDividersEnabled

      public void setHeaderDividersEnabled(boolean headerDividersEnabled)
      Enables or disables the drawing of the divider for header views.
      Parameters:
      headerDividersEnabled - True to draw the headers, false otherwise.
      See Also:
    • areHeaderDividersEnabled

      public boolean areHeaderDividersEnabled()
      Returns:
      Whether the drawing of the divider for header views is enabled
      See Also:
    • setFooterDividersEnabled

      public void setFooterDividersEnabled(boolean footerDividersEnabled)
      Enables or disables the drawing of the divider for footer views.
      Parameters:
      footerDividersEnabled - True to draw the footers, false otherwise.
      See Also:
    • areFooterDividersEnabled

      public boolean areFooterDividersEnabled()
      Returns:
      Whether the drawing of the divider for footer views is enabled
      See Also:
    • setOverscrollHeader

      public void setOverscrollHeader(Drawable header)
      Sets the drawable that will be drawn above all other list content. This area can become visible when the user overscrolls the list.
      Parameters:
      header - The drawable to use
    • getOverscrollHeader

      public Drawable getOverscrollHeader()
      Returns:
      The drawable that will be drawn above all other list content
    • setOverscrollFooter

      public void setOverscrollFooter(Drawable footer)
      Sets the drawable that will be drawn below all other list content. This area can become visible when the user overscrolls the list, or when the list's content does not fully fill the container area.
      Parameters:
      footer - The drawable to use
    • getOverscrollFooter

      public Drawable getOverscrollFooter()
      Returns:
      The drawable that will be drawn below all other list content
    • onFocusChanged

      protected void onFocusChanged(boolean gainFocus, int direction, @Nullable Rect previouslyFocusedRect)
      Description copied from class: View
      Called by the view system when the focus state of this view changes. When the focus change event is caused by directional navigation, direction and previouslyFocusedRect provide insight into where the focus is coming from. When overriding, be sure to call up through to the super class so that the standard focus handling will occur.
      Overrides:
      onFocusChanged in class AbsListView
      Parameters:
      gainFocus - True if the View has focus; false otherwise.
      direction - The direction focus has moved when requestFocus() is called to give this view focus. Values are View.FOCUS_UP, View.FOCUS_DOWN, View.FOCUS_LEFT, View.FOCUS_RIGHT, View.FOCUS_FORWARD, or View.FOCUS_BACKWARD. It may not always apply, in which case use the default.
      previouslyFocusedRect - The rectangle, in this view's coordinate system, of the previously focused view. If applicable, this will be passed in as finer grained information about where the focus is coming from (in addition to direction). Will be null otherwise.
    • findViewTraversal

      @Nullable protected <T extends View> T findViewTraversal(int id)
      Overrides:
      findViewTraversal in class ViewGroup
      Parameters:
      id - the id of the view to be found
      Returns:
      the view of the specified id, null if cannot be found
      See Also:
    • findViewByPredicateTraversal

      protected <T extends View> T findViewByPredicateTraversal(@NonNull Predicate<View> predicate, View childToSkip)
      First look in our children, then in any header and footer views that may be scrolled off.
      Overrides:
      findViewByPredicateTraversal in class ViewGroup
      Parameters:
      predicate - The predicate to evaluate.
      childToSkip - If not null, ignores this child during the recursive traversal.
      Returns:
      The first view that matches the predicate or null.
      See Also:
    • wrapHeaderListAdapterInternal

      @Internal @NonNull protected HeaderViewListAdapter wrapHeaderListAdapterInternal(ArrayList<ListView.FixedViewInfo> headerViewInfos, ArrayList<ListView.FixedViewInfo> footerViewInfos, ListAdapter adapter)
    • wrapHeaderListAdapterInternal

      @Internal protected void wrapHeaderListAdapterInternal()
    • dispatchDataSetObserverOnChangedInternal

      @Internal protected void dispatchDataSetObserverOnChangedInternal()