Android
android.widget
public class

android.widget.ListView

java.lang.Object
android.view.View Drawable.Callback KeyEvent.Callback
android.view.ViewGroup ViewManager ViewParent
android.widget.AdapterView<T extends android.widget.Adapter>
android.widget.AbsListView TextWatcher ViewTreeObserver.OnGlobalLayoutListener ViewTreeObserver.OnTouchModeChangeListener Filter.FilterListener
android.widget.ListView

A view that shows items in a vertically scrolling list. The items come from the ListAdapter associated with this view.

Known Direct Subclasses

Summary

XML Attributes

Attribute name Related methods  
android:choiceMode   Defines the choice behavior for the List. 
android:divider   Drawable or color to draw between list items. 
android:dividerHeight   Height of the divider. 
android:entries   Reference to an array resource that will populate the ListView. 
XML Attributes inherited from class android.widget.AbsListView
XML Attributes inherited from class android.view.ViewGroup
XML Attributes inherited from class android.view.View

Constants

      Value  
int  CHOICE_MODE_MULTIPLE  The list allows multiple choices   0x00000002 
int  CHOICE_MODE_NONE  Normal list that does not indicate choices   0x00000000 
int  CHOICE_MODE_SINGLE  The list allows up to one choice   0x00000001 
Constants inherited from class android.widget.AbsListView
Constants inherited from class android.widget.AdapterView
Constants inherited from class android.view.ViewGroup
Constants inherited from class android.view.View
Fields inherited from class android.widget.AdapterView
Fields inherited from class android.view.ViewGroup
Fields inherited from class android.view.View

Public Constructors

            ListView(Context context)
            ListView(Context context, AttributeSet attrs)
            ListView(Context context, AttributeSet attrs, int defStyle)

Public Methods

          void  addFooterView(View v)
Add a fixed view to appear at the bottom of the list.
          void  addFooterView(View v, Object data, boolean isSelectable)
Add a fixed view to appear at the bottom of the list.
          void  addHeaderView(View v)
Add a fixed view to appear at the top of the list.
          void  addHeaderView(View v, Object data, boolean isSelectable)
Add a fixed view to appear at the top of the list.
          void  clearChoices()
Clear any choices previously set
          boolean  dispatchKeyEvent(KeyEvent event)
Dispatch a key event to the next view on the focus path.
          ListAdapter  getAdapter()
Returns the adapter currently in use in this ListView.
          int  getCheckedItemPosition()
Returns the currently checked item.
          SparseBooleanArray  getCheckedItemPositions()
Returns the set of checked items in the list.
          int  getChoiceMode()
          Drawable  getDivider()
Returns the drawable that will be drawn between each item in the list.
          int  getDividerHeight()
          int  getFooterViewsCount()
Returns the number of footer views in the list.
          int  getHeaderViewsCount()
Returns the number of header views in the list.
          boolean  getItemsCanFocus()
          int  getMaxScrollAmount()
          boolean  isItemChecked(int position)
Returns the checked state of the specified position.
          boolean  onKeyDown(int keyCode, KeyEvent event)
Default implementation of KeyEvent.Callback.onKeyMultiple(): perform press of the view when KEYCODE_DPAD_CENTER or KEYCODE_ENTER is released, if the view is enabled and clickable.
          boolean  onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handle the event).
          boolean  onKeyUp(int keyCode, KeyEvent event)
Default implementation of KeyEvent.Callback.onKeyMultiple(): perform clicking of the view when KEYCODE_DPAD_CENTER or KEYCODE_ENTER is released.
          void  onRestoreInstanceState(Parcelable state)
Hook allowing a view to re-apply a representation of its internal state that had previously been generated by onSaveInstanceState().
          Parcelable  onSaveInstanceState()
Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state.
          boolean  onTouchEvent(MotionEvent ev)
Implement this method to handle touch screen motion events.
          boolean  performItemClick(View view, int position, long id)
Call the OnItemClickListener, if it is defined.
          boolean  removeFooterView(View v)
Removes a previously-added footer view.
          boolean  removeHeaderView(View v)
Removes a previously-added header view.
          boolean  requestChildRectangleOnScreen(View child, Rect rect, boolean immediate)
Called when a child of this group wants a particular rectangle to be positioned onto the screen.
          void  setAdapter(ListAdapter adapter)
Sets the data behind this ListView.
          void  setChoiceMode(int choiceMode)
Defines the choice behavior for the List.
          void  setDivider(Drawable divider)
Sets the drawable that will be drawn between each item in the list.
          void  setDividerHeight(int height)
Sets the height of the divider that will be drawn between each item in the list.
          void  setItemChecked(int position, boolean value)
Sets the checked state of the specified position.
          void  setItemsCanFocus(boolean itemsCanFocus)
Indicates that the views created by the ListAdapter can contain focusable items.
          void  setSelection(int position)
Sets the currently selected item
          void  setSelectionAfterHeaderView()
setSelectionAfterHeaderView set the selection to be the first list item after the header views.
          void  setSelectionFromTop(int position, int y)
Sets the selected item and positions the selection y pixels from the top edge of the ListView.

Protected Methods

          boolean  canAnimate()
Indicates whether the view group has the ability to animate its children after the first layout.
          void  dispatchDraw(Canvas canvas)
Called by draw to draw the child views.
          View  findViewTraversal(int id)
          View  findViewWithTagTraversal(Object tag)
          void  layoutChildren()
          void  onFinishInflate()
Finalize inflating a view from XML.
          void  onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect)
Called by the view system when the focus state of this view changes.
          void  onMeasure(int widthMeasureSpec, int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height.

Methods inherited from class android.widget.AbsListView
Methods inherited from class android.widget.AdapterView
Methods inherited from class android.view.ViewGroup
Methods inherited from class android.view.View
Methods inherited from class java.lang.Object
Methods inherited from interface android.graphics.drawable.Drawable.Callback
Methods inherited from interface android.text.TextWatcher
Methods inherited from interface android.view.KeyEvent.Callback
Methods inherited from interface android.view.ViewManager
Methods inherited from interface android.view.ViewParent
Methods inherited from interface android.view.ViewTreeObserver.OnGlobalLayoutListener
Methods inherited from interface android.view.ViewTreeObserver.OnTouchModeChangeListener
Methods inherited from interface android.widget.Filter.FilterListener

Details

XML Attributes

android:choiceMode

Defines the choice behavior for the List. By default, Lists do not have any choice behavior. By setting the choiceMode to singleChoice, the List allows up to one item to be in a chosen state. By setting the choiceMode to multipleChoice, the list allows any number of items to be chosen.

Must be one of the following constant values.

ConstantValueDescription
none0 Normal list that does not indicate choices
singleChoice1 The list allows up to one choice
multipleChoice2 The list allows multiple choices

This corresponds to the global attribute resource symbol choiceMode.

Related Methods

android:divider

Drawable or color to draw between list items.

May be a reference to another resource, in the form "@[+][package:]type:name" or to a theme attribute in the form "?[package:][type:]name".

May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

This corresponds to the global attribute resource symbol divider.

Related Methods

android:dividerHeight

Height of the divider. Will use the intrinsic height of the divider if this is not specified.

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), db (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol dividerHeight.

Related Methods

android:entries

Reference to an array resource that will populate the ListView. For static content, this is simpler than populating the ListView programmatically.

Must be a reference to another resource, in the form "@[+][package:]type:name" or to a theme attribute in the form "?[package:][type:]name".

This corresponds to the global attribute resource symbol entries.

Related Methods

Constants

public static final int CHOICE_MODE_MULTIPLE

The list allows multiple choices
Constant Value: 2 (0x00000002)

public static final int CHOICE_MODE_NONE

Normal list that does not indicate choices
Constant Value: 0 (0x00000000)

public static final int CHOICE_MODE_SINGLE

The list allows up to one choice
Constant Value: 1 (0x00000001)

Public Constructors

public ListView(Context context)

public ListView(Context context, AttributeSet attrs)

public ListView(Context context, AttributeSet attrs, int defStyle)

Public Methods

public void addFooterView(View v)

Add a fixed view to appear at the bottom of the list. If addFooterView 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.

NOTE: Call this before calling setAdapter. This is so ListView can wrap the supplied cursor with one that that will also account for header views.

Parameters

v The view to add.

public void addFooterView(View v, Object data, boolean isSelectable)

Add a fixed view to appear at the bottom of the list. If addFooterView 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.

NOTE: Call this before calling setAdapter. This is so ListView can wrap the supplied cursor with one that that will also account for header views.

Parameters

v The view to add.
data Data to associate with this view
isSelectable true if the footer view can be selected

public void addHeaderView(View v)

Add a fixed view to appear at the top of the list. If addHeaderView 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.

NOTE: Call this before calling setAdapter. This is so ListView can wrap the supplied cursor with one that that will also account for header views.

Parameters

v The view to add.

public void addHeaderView(View v, Object data, boolean isSelectable)

Add a fixed view to appear at the top of the list. If addHeaderView 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.

NOTE: Call this before calling setAdapter. This is so ListView can wrap the supplied cursor with one that that will also account for header views.

Parameters

v The view to add.
data Data to associate with this view
isSelectable whether the item is selectable

public void clearChoices()

Clear any choices previously set

public boolean dispatchKeyEvent(KeyEvent event)

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.

Parameters

event The key event to be dispatched.

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.

Returns

  • The adapter currently used to display data in this ListView.

public int getCheckedItemPosition()

Returns the currently checked item. The result is only valid if the choice mode has not been set to CHOICE_MODE_SINGLE.

Returns

  • The position of the currently checked item or INVALID_POSITION if nothing is selected

public SparseBooleanArray getCheckedItemPositions()

Returns the set of checked items in the list. The result is only valid if the choice mode has not been set to CHOICE_MODE_SINGLE.

Returns

  • A SparseBooleanArray which will return true for each call to get(int position) where position is a position in the list.

public int getChoiceMode()

Returns

  • The current choice mode

public Drawable getDivider()

Returns the drawable that will be drawn between each item in the list.

Returns

  • the current drawable drawn between list elements

public int getDividerHeight()

Returns

  • Returns the height of the divider that will be drawn between each item in the list.

public int getFooterViewsCount()

Returns the number of footer views in the list. Footer views are special views at the bottom of the list that should not be recycled during a layout.

Returns

  • The number of footer views, 0 in the default implementation.

public int getHeaderViewsCount()

Returns the number of header views in the list. Header views are special views at the top of the list that should not be recycled during a layout.

Returns

  • The number of header views, 0 in the default implementation.

public boolean getItemsCanFocus()

Returns

  • Whether the views created by the ListAdapter can contain focusable items.

public int getMaxScrollAmount()

Returns

  • The maximum amount a list view will scroll in response to an arrow event.

public boolean isItemChecked(int position)

Returns the checked state of the specified position. The result is only valid if the choice mode has not been set to CHOICE_MODE_SINGLE or CHOICE_MODE_MULTIPLE.

Parameters

position The item whose checked state to return

Returns

  • The item's checked state

public boolean onKeyDown(int keyCode, KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyMultiple(): perform press of the view when KEYCODE_DPAD_CENTER or KEYCODE_ENTER is released, if the view is enabled and clickable.

Parameters

keyCode A key code that represents the button pressed, from KeyEvent.
event The KeyEvent object that defines the button action.

public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handle the event).

Parameters

keyCode A key code that represents the button pressed, from KeyEvent.
repeatCount The number of times the action was made.
event The KeyEvent object that defines the button action.

public boolean onKeyUp(int keyCode, KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyMultiple(): perform clicking of the view when KEYCODE_DPAD_CENTER or KEYCODE_ENTER is released.

Parameters

keyCode A key code that represents the button pressed, from KeyEvent.
event The KeyEvent object that defines the button action.

public void onRestoreInstanceState(Parcelable state)

Hook allowing a view to re-apply a representation of its internal state that had previously been generated by onSaveInstanceState(). This function will never be called with a null state.

Parameters

state The frozen state that had previously been returned by onSaveInstanceState().

public Parcelable onSaveInstanceState()

Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

Some examples of things you may store here: the current cursor position in a text view (but usually not the text itself since that is stored in a content provider or other persistent storage), the currently selected item in a list view.

public boolean onTouchEvent(MotionEvent ev)

Implement this method to handle touch screen motion events.

Parameters

ev The motion event.

public boolean performItemClick(View view, int position, long id)

Call the OnItemClickListener, if it is defined.

Parameters

view The view within the AdapterView that was clicked.
position The position of the view in the adapter.
id The row id of the item that was clicked.

Returns

  • True if there was an assigned OnItemClickListener that was called, false otherwise is returned.

public boolean removeFooterView(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

public boolean removeHeaderView(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

public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate)

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 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
    • 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

public void setAdapter(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.

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

public void setChoiceMode(int choiceMode)

Defines the choice behavior for the List. By default, Lists do not have any choice behavior (CHOICE_MODE_NONE). By setting the choiceMode to CHOICE_MODE_SINGLE, the List allows up to one item to be in a chosen state. By setting the choiceMode to CHOICE_MODE_MULTIPLE, the list allows any number of items to be chosen.

Parameters

choiceMode One of CHOICE_MODE_NONE, CHOICE_MODE_SINGLE, or CHOICE_MODE_MULTIPLE

public void setDivider(Drawable divider)

Sets the drawable that will be drawn between each item in the list. If the drawable does not have an intrinsic height, you should also call setDividerHeight(int)

Parameters

divider The drawable to use.

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.

public void setItemChecked(int position, boolean value)

Sets the checked state of the specified position. The is only valid if the choice mode has been set to CHOICE_MODE_SINGLE or CHOICE_MODE_MULTIPLE.

Parameters

position The item whose checked state is to be checked
value The new checked sate for the item

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

public void setSelection(int position)

Sets the currently selected item

Parameters

position Index (starting at 0) of the data item to be selected. If in touch mode, the item will not be selected but it will still be positioned appropriately.

public void setSelectionAfterHeaderView()

setSelectionAfterHeaderView set the selection to be the first list item after the header views.

public void setSelectionFromTop(int position, int y)

Sets the selected item and positions the selection y pixels from the top edge of the ListView. (If in touch mode, the item will not be selected but it will still be positioned appropriately.)

Parameters

position Index (starting at 0) of the data item to be selected.
y The distance from the top edge of the ListView (plus padding) that the item will be positioned.

Protected Methods

protected boolean canAnimate()

Indicates whether the view group has the ability to animate its children after the first layout.

protected void dispatchDraw(Canvas canvas)

Called by draw to draw the child views. This may be overridden by derived classes to gain control just before its children are drawn (but after its own view has been drawn).

Parameters

canvas the canvas on which to draw the view

protected View findViewTraversal(int id)

Parameters

id the id of the view to be found

protected View findViewWithTagTraversal(Object tag)

Parameters

tag the tag of the view to be found

protected void layoutChildren()

protected void onFinishInflate()

Finalize inflating a view from XML. This is called as the last phase of inflation, after all child views have been added.

Even if the subclass overrides onFinishInflate, they should always be sure to call the super method, so that we get called.

protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect)

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.

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 or View.FOCUS_RIGHT. 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.

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height. This method is invoked by measure(int, int) and should be overriden by subclasses to provide accurate and efficient measurement of their contents.

CONTRACT: When overriding this method, you must call setMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger an IllegalStateException, thrown by measure(int, int). Calling the superclass' onMeasure(int, int) 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 onMeasure(int, int) to provide better measurements of their content.

If this method is overridden, it is the subclass's responsibility to make sure the measured height and width are at least the view's minimum height and width (getSuggestedMinimumHeight() and getSuggestedMinimumWidth()).

Parameters

widthMeasureSpec horizontal space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.
heightMeasureSpec vertical space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.
Copyright 2007 Google Inc. Build 0.9_r1-98467 - 14 Aug 2008 18:48