get Item Position within Adapter - Android android.widget

Android examples for android.widget:Adapter

Description

get Item Position within Adapter

Demo Code

import android.widget.Adapter;

public class Main {

  public static final int INVALID_POSITION = -1;

  /**/*from w w  w .jav a  2  s  . c  o  m*/
   * @param adapter
   *          - adapter with objects to be searched
   * @param object
   *          - object to search in adapter
   * @return position of item or -1 if item is not in adapter
   */
  public static int getItemPosition(Adapter adapter, Object object) {
    return getItemPosition(adapter, object, INVALID_POSITION);
  }

  /**
   *
   * @param adapter
   *          - adapter with objects to be searched
   * @param object
   *          - object to search in adapter
   * @param defaultPosition
   *          - default position to return if object is not in adapter
   * @return position of item or default position if item is not in adapter
   */
  public static int getItemPosition(Adapter adapter, Object object, int defaultPosition) {
    int position = defaultPosition;
    for (int i = 0; i < adapter.getCount(); i++) {
      if (adapter.getItem(i).equals(object)) {
        position = i;
        break;
      }
    }
    return position;
  }

}

Related Tutorials