text: //
  //  AdapterView::h
  //  cocos2dx
  //
  //  Created by Saul Howard on 12/11/13.
  //  Copyright (c) 2013 cocos2d-x. All rights reserved.
  //
  
  #ifndef __cocos2dx__AdapterView__
  #define __cocos2dx__AdapterView__
  
  #include "AndroidMacros.h"
  
  #include "Android/widget/Adapter.h"
  #include "Android/view/ViewGroup.h"
  #include "Android/database/DataSetObserver.h"
  #include "Android/utils/Exceptions.h"
  
  #include <mindroid/os/Runnable.h>
  #include <mindroid/os/Clock.h>
  
  #include <algorithm>
  
  using namespace mindroid;
  
  ANDROID_BEGIN
  
  template<class T>
  class AdapterView : public ViewGroup {
      
  public:
      /**
       * The item view type returned by {@link Adapter#getItemViewType(int)} when
       * the adapter does not want the item's view recycled.
       */
      static const int ITEM_VIEW_TYPE_IGNORE = -1;
      
      /**
       * The item view type returned by {@link Adapter#getItemViewType(int)} when
       * the item is a header or footer.
       */
      static const int ITEM_VIEW_TYPE_HEADER_OR_FOOTER = -2;
      
      /**
       * Represents an invalid position. All valid positions are in the range 0 to 1 less than the
       * number of items in the current adapter->
       */
      static const int INVALID_POSITION = -1;
      
      /**
       * Represents an empty or invalid row id
       */
      static const long INVALID_ROW_ID = LONG_MIN;
      
      AdapterView(Context *context) : ViewGroup(context) {
      }
      
      AdapterView(Context *context, AttributeSet *attrs) : ViewGroup(context, attrs) {
      }
      
      /**
       * Interface definition for a callback to be invoked when an item in this
       * AdapterView has been clicked.
       */
      class OnItemClickListener {
      public:
          /**
           * Callback method to be invoked when an item in this AdapterView has
           * been clicked.
           * <p>
           * Implementers can call getItemAtPosition(position) if they need
           * to access the data associated with the selected item.
           *
           * @param parent The AdapterView where the click happened.
           * @param view The view within the AdapterView that was clicked (this
           *            will be a view provided by the adapter)
           * @param position The position of the view in the adapter->
           * @param id The row id of the item that was clicked.
           */
          virtual void onItemClick(AdapterView<T> *parent, View *view, int position, long id) = 0;
      };
      
      /**
       * Register a callback to be invoked when an item in this AdapterView has
       * been clicked.
       *
       * @param listener The callback that will be invoked.
       */
      void setOnItemClickListener(OnItemClickListener *listener) {
          mOnItemClickListener = listener;
      }
      
      /**
       * @return The callback to be invoked with an item in this AdapterView has
       *         been clicked, or NULL id no callback has been set.
       */
      OnItemClickListener *getOnItemClickListener() {
          return mOnItemClickListener;
      }
      
      /**
       * Call the OnItemClickListener, if it is defined.
       *
       * @param view The view within the AdapterView that was clicked.
       * @param position The position of the view in the adapter->
       * @param id The row id of the item that was clicked.
       * @return True if there was an assigned OnItemClickListener that was
       *         called, false otherwise is returned.
       */
      virtual bool performItemClick(View *view, int position, long id) {
          if (mOnItemClickListener) {
  //            playSoundEffect(SoundEffectConstants.CLICK);
              
              mOnItemClickListener->onItemClick(this, view, position, id);
              return true;
          }
          
          return false;
      }
      
      /**
       * Interface definition for a callback to be invoked when an item in this
       * view has been clicked and held.
       */
      class OnItemLongClickListener {
      public:
          /**
           * Callback method to be invoked when an item in this view has been
           * clicked and held.
           *
           * Implementers can call getItemAtPosition(position) if they need to access
           * the data associated with the selected item.
           *
           * @param parent The AbsListView where the click happened
           * @param view The view within the AbsListView that was clicked
           * @param position The position of the view in the list
           * @param id The row id of the item that was clicked
           *
           * @return true if the callback consumed the long click, false otherwise
           */
          virtual bool onItemLongClick(AdapterView<T> *parent, View *view, int position, long id) = 0;
      };
      
      
      /**
       * Register a callback to be invoked when an item in this AdapterView has
       * been clicked and held
       *
       * @param listener The callback that will run
       */
      void setOnItemLongClickListener(OnItemLongClickListener *listener) {
          if (!isLongClickable()) {
              setLongClickable(true);
          }
          mOnItemLongClickListener = listener;
      }
      
      /**
       * @return The callback to be invoked with an item in this AdapterView has
       *         been clicked and held, or NULL id no callback as been set.
       */
      const OnItemLongClickListener *getOnItemLongClickListener() {
          return mOnItemLongClickListener;
      }
      
      /**
       * Interface definition for a callback to be invoked when
       * an item in this view has been selected.
       */
      class OnItemSelectedListener {
      public:
          /**
           * <p>Callback method to be invoked when an item in this view has been
           * selected. This callback is invoked only when the newly selected
           * position is different from the previously selected position or if
           * there was no selected item.</p>
           *
           * Impelmenters can call getItemAtPosition(position) if they need to access the
           * data associated with the selected item.
           *
           * @param parent The AdapterView where the selection happened
           * @param view The view within the AdapterView that was clicked
           * @param position The position of the view in the adapter
           * @param id The row id of the item that is selected
           */
          virtual void onItemSelected(AdapterView<T> *parent, View *view, int position, long id) = 0;
          
          /**
           * Callback method to be invoked when the selection disappears from this
           * View:: The selection can disappear for instance when touch is activated
           * or when the adapter becomes empty.
           *
           * @param parent The AdapterView that now contains no selected item.
           */
          virtual void onNothingSelected(AdapterView<T> *parent) = 0;
      };
      
      
      /**
       * Register a callback to be invoked when an item in this AdapterView has
       * been selected.
       *
       * @param listener The callback that will run
       */
      void setOnItemSelectedListener(OnItemSelectedListener *listener) {
          mOnItemSelectedListener = listener;
      }
      
      const OnItemSelectedListener *getOnItemSelectedListener() {
          return mOnItemSelectedListener;
      }
      
      /**
       * Extra menu information provided to the
       * {@link android.View::View::OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo) }
       * callback when a context menu is brought up for this AdapterView::
       *
       */
  //    class AdapterContextMenuInfo : public ContextMenu.ContextMenuInfo {
  //        
  //        AdapterContextMenuInfo(View targetView, int position, long id) {
  //            this.targetView = targetView;
  //            this.position = position;
  //            this.id = id;
  //        }
  //        
  //        /**
  //         * The child view for which the context menu is being displayed. This
  //         * will be one of the children of this AdapterView::
  //         */
  //        View targetView;
  //        
  //        /**
  //         * The position in the adapter for which the context menu is being
  //         * displayed.
  //         */
  //        int position;
  //        
  //        /**
  //         * The row id of the item for which the context menu is being displayed.
  //         */
  //        long id;
  //    }
      
      /**
       * Returns the adapter currently associated with this widget.
       *
       * @return The adapter used to provide this view's content.
       */
      virtual shared_ptr<T> getAdapter() = 0;
      
      /**
       * Sets the adapter that provides the data and the views to represent the data
       * in this widget.
       *
       * @param adapter The adapter to use to create this view's content.
       */
      virtual void setAdapter(shared_ptr<T> adapter) = 0;
      
      /**
       * This method is not supported and throws an UnsupportedOperationException when called.
       *
       * @param child Ignored.
       *
       * @throws UnsupportedOperationException Every time this method is invoked.
       */
      virtual void addView(View *child) {
          throw UnsupportedOperationException("addView(View) is not supported in AdapterView");
      }
      
      /**
       * This method is not supported and throws an UnsupportedOperationException when called.
       *
       * @param child Ignored.
       * @param index Ignored.
       *
       * @throws UnsupportedOperationException Every time this method is invoked.
       */
      virtual void addView(View *child, int index) {
          throw UnsupportedOperationException("addView(View, int) is not supported in AdapterView");
      }
      
      /**
       * This method is not supported and throws an UnsupportedOperationException when called.
       *
       * @param child Ignored.
       * @param params Ignored.
       *
       * @throws UnsupportedOperationException Every time this method is invoked.
       */
      virtual void addView(View *child, LayoutParams *params) {
          throw UnsupportedOperationException("addView(View, LayoutParams) is not supported in AdapterView");
      }
      
      /**
       * This method is not supported and throws an UnsupportedOperationException when called.
       *
       * @param child Ignored.
       * @param index Ignored.
       * @param params Ignored.
       *
       * @throws UnsupportedOperationException Every time this method is invoked.
       */
      virtual void addView(View *child, int index, LayoutParams *params) {
          throw UnsupportedOperationException("addView(View, int, LayoutParams) is not supported in AdapterView");
      }
      
      /**
       * This method is not supported and throws an UnsupportedOperationException when called.
       *
       * @param child Ignored.
       *
       * @throws UnsupportedOperationException Every time this method is invoked.
       */
      virtual void removeView(View *child) {
          throw UnsupportedOperationException("removeView(View) is not supported in AdapterView");
      }
      
      /**
       * This method is not supported and throws an UnsupportedOperationException when called.
       *
       * @param index Ignored.
       *
       * @throws UnsupportedOperationException Every time this method is invoked.
       */
      virtual void removeViewAt(int index) {
          throw UnsupportedOperationException("removeViewAt(int) is not supported in AdapterView");
      }
      
      /**
       * This method is not supported and throws an UnsupportedOperationException when called.
       *
       * @throws UnsupportedOperationException Every time this method is invoked.
       */
      virtual void removeAllViews() {
          throw UnsupportedOperationException("removeAllViews() is not supported in AdapterView");
      }
      
      /**
       * Return the position of the currently selected item within the adapter's data set
       *
       * @return int Position (starting at 0), or {@link #INVALID_POSITION} if there is nothing selected.
       */
      int getSelectedItemPosition() {
          return mNextSelectedPosition;
      }
      
      /**
       * @return The id corresponding to the currently selected item, or {@link #INVALID_ROW_ID}
       * if nothing is selected.
       */
      long getSelectedItemId() {
          return mNextSelectedRowId;
      }
      
      /**
       * @return The view corresponding to the currently selected item, or NULL
       * if nothing is selected
       */
      virtual View *getSelectedView() = 0;
      
      /**
       * @return The data corresponding to the currently selected item, or
       * NULL if there is nothing selected.
       */
      shared_ptr<Object> getSelectedItem() {
          shared_ptr<T> adapter = getAdapter();
          int selection = getSelectedItemPosition();
          if (adapter && adapter->getCount() > 0 && selection >= 0) {
              return adapter->getItem(selection);
          } else {
              return NULL;
          }
      }
      
      /**
       * @return The number of items owned by the Adapter associated with this
       *         AdapterView:: (This is the number of data items, which may be
       *         larger than the number of visible views.)
       */
      int getCount() {
          return mItemCount;
      }
      
      /**
       * Get the position within the adapter's data set for the view, where view is a an adapter item
       * or a descendant of an adapter item.
       *
       * @param view an adapter item, or a descendant of an adapter item. This must be visible in this
       *        AdapterView at the time of the call.
       * @return the position within the adapter's data set of the view, or {@link #INVALID_POSITION}
       *         if the view does not correspond to a list item (or it is not currently visible).
       */
      int getPositionForView(View *view) {
          View *listItem = view;
          try {
              View *v = NULL;
              while ((v = (View*) listItem->getParent().get()) != this) {
                  listItem = v;
              }
          } catch (Exception e) {
              // We made it up to the window without find this list view
              return INVALID_POSITION;
          }
          
          // Search the children for the list item
          const int childCount = getChildCount();
          for (int i = 0; i < childCount; i++) {
              if (getChildAt(i).equals(listItem)) {
                  return mFirstPosition + i;
              }
          }
          
          // Child not found!
          return INVALID_POSITION;
      }
      
      /**
       * Returns the position within the adapter's data set for the first item
       * displayed on screen.
       *
       * @return The position within the adapter's data set
       */
      int getFirstVisiblePosition() {
          return mFirstPosition;
      }
      
      /**
       * Returns the position within the adapter's data set for the last item
       * displayed on screen.
       *
       * @return The position within the adapter's data set
       */
      int getLastVisiblePosition() {
          return mFirstPosition + getChildCount() - 1;
      }
      
      /**
       * Sets the currently selected item. To support accessibility subclasses that
       * override this method must invoke the overriden super method first.
       *
       * @param position Index (starting at 0) of the data item to be selected.
       */
      virtual void setSelection(int position) = 0;
      
      /**
       * Sets the view to show if the adapter is empty
       */
      void setEmptyView(View *emptyView) {
          mEmptyView = emptyView;
          
          shared_ptr<T> adapter = getAdapter();
          const bool empty = ((adapter == NULL) || adapter->isEmpty());
          updateEmptyStatus(empty);
      }
      
      /**
       * When the current adapter is empty, the AdapterView can display a special view
       * call the empty View:: The empty view is used to provide feedback to the user
       * that no data is available in this AdapterView::
       *
       * @return The view to show if the adapter is empty.
       */
      View *getEmptyView() {
          return mEmptyView;
      }
      
  //    virtual void setFocusable(bool focusable) {
  //        const Adapter *adapter = (Adapter*) getAdapter();
  //        const bool empty = adapter == NULL || adapter->getCount() == 0;
  //        
  //        mDesiredFocusableState = focusable;
  //        if (!focusable) {
  //            mDesiredFocusableInTouchModeState = false;
  //        }
  //        
  //        ViewGroup::setFocusable(focusable && (!empty || isInFilterMode()));
  //    }
  //    
  //    virtual void setFocusableInTouchMode(bool focusable) {
  //        const Adapter *adapter = (Adapter*) getAdapter();
  //        const bool empty = adapter == NULL || adapter->getCount() == 0;
  //        
  //        mDesiredFocusableInTouchModeState = focusable;
  //        if (focusable) {
  //            mDesiredFocusableState = true;
  //        }
  //        
  //        ViewGroup::setFocusableInTouchMode(focusable && (!empty || isInFilterMode()));
  //    }
      
      /**
       * Gets the data associated with the specified position in the list.
       *
       * @param position Which data to get
       * @return The data associated with the specified position in the list
       */
      shared_ptr<Object> getItemAtPosition(int position) {
          shared_ptr<T> adapter = getAdapter();
          return (adapter == NULL || position < 0) ? NULL : adapter->getItem(position);
      }
      
      long getItemIdAtPosition(int position) {
          shared_ptr<T> adapter = getAdapter();
          return (adapter == NULL || position < 0) ? INVALID_ROW_ID : adapter->getItemId(position);
      }
      
      virtual void setOnClickListener(std::function<void (View&)> onClickListener) {
          throw RuntimeException("Don't call setOnClickListener for an AdapterView:: You probably want setOnItemClickListener instead");
      }
  
  protected:
      /**
       * The position of the first child displayed
       */
      int mFirstPosition = 0;
      
      /**
       * The offset in pixels from the top of the AdapterView to the top
       * of the view to select during the next layout.
       */
      int mSpecificTop = 0;
      
      /**
       * Position from which to start looking for mSyncRowId
       */
      int mSyncPosition = 0;
      
      /**
       * Row id to look for when data has changed
       */
      long mSyncRowId = INVALID_ROW_ID;
      
      /**
       * Height of the view when mSyncPosition and mSyncRowId where set
       */
      long mSyncHeight = 0;
      
      /**
       * True if we need to sync to mSyncRowId
       */
      bool mNeedSync = false;
      
      /**
       * Indicates whether to sync based on the selection or position. Possible
       * values are {@link #SYNC_SELECTED_POSITION} or
       * {@link #SYNC_FIRST_POSITION}.
       */
      int mSyncMode = 0;
      
  private:
      
      /**
       * Our height after the last layout
       */
      int mLayoutHeight = 0;
      
  protected:
      
      /**
       * Sync based on the selected child
       */
      static const int SYNC_SELECTED_POSITION = 0;
      
      /**
       * Sync based on the first child displayed
       */
      static const int SYNC_FIRST_POSITION = 1;
      
      /**
       * Maximum amount of time to spend in {@link #findSyncPosition()}
       */
      static const int SYNC_MAX_DURATION_MILLIS = 100;
      
      /**
       * Indicates that this view is currently being laid out.
       */
      bool mInLayout = false;
      
      /**
       * The listener that receives notifications when an item is selected.
       */
      OnItemSelectedListener *mOnItemSelectedListener = NULL;
      
      /**
       * The listener that receives notifications when an item is clicked.
       */
      OnItemClickListener *mOnItemClickListener = NULL;
      
      /**
       * The listener that receives notifications when an item is long clicked.
       */
      OnItemLongClickListener *mOnItemLongClickListener = NULL;
  
  protected:
      /**
       * True if the data has changed since the last layout
       */
      bool mDataChanged = false;
      
      /**
       * The position within the adapter's data set of the item to select
       * during the next layout.
       */
      int mNextSelectedPosition = INVALID_POSITION;
      
      /**
       * The item id of the item to select during the next layout.
       */
      long mNextSelectedRowId = INVALID_ROW_ID;
      
      /**
       * The position within the adapter's data set of the currently selected item.
       */
      int mSelectedPosition = INVALID_POSITION;
      
      /**
       * The item id of the currently selected item.
       */
      long mSelectedRowId = INVALID_ROW_ID;
  
  private:
      /**
       * View to show if there are no items to show.
       */
      View *mEmptyView = NULL;
  
  protected:
      /**
       * The number of items in the current adapter->
       */
      int mItemCount = 0;
  
      /**
       * The number of items in the adapter before a data changed event occurred.
       */
      int mOldItemCount = 0;
      
      /**
       * The last selected position we used when notifying
       */
      int mOldSelectedPosition = INVALID_POSITION;
      
      /**
       * The id of the last selected position we used when notifying
       */
      long mOldSelectedRowId = INVALID_ROW_ID;
      
  private:
  
      /**
       * Indicates what focusable state is requested when calling setFocusable().
       * In addition to this, this view has other criteria for actually
       * determining the focusable state (such as whether its empty or the text
       * filter is shown).
       *
       * @see #setFocusable(bool)
       * @see #checkFocus()
       */
      bool mDesiredFocusableState = false;
      bool mDesiredFocusableInTouchModeState = false;
      
      class SelectionNotifier : public Runnable {
          
      public:
          
          SelectionNotifier(AdapterView<T> *adapterView) {
              mAdapterView = adapterView;
          }
          
          virtual void run() {
              if (mAdapterView->mDataChanged) {
                  // Data has changed between when this SelectionNotifier
                  // was posted and now. We need to wait until the AdapterView
                  // has been synched to the new data.
                  if (mAdapterView->getAdapter() != NULL) {
                      mAdapterView->post(this);
                  }
              } else {
                  mAdapterView->fireOnSelected();
              }
          }
          
      private:
          AdapterView<T> *mAdapterView = NULL;
      };
      
      SelectionNotifier *mSelectionNotifier = NULL;
      
  protected:
      /**
       * When set to true, calls to requestLayout() will not propagate up the parent hierarchy.
       * This is used to layout the children during a layout pass.
       */
      bool mBlockLayoutRequests = false;
      
      /**
       * Indicates whether this view is in filter mode. Filter mode can for instance
       * be enabled by a user when typing on the keyboard.
       *
       * @return True if the view is in filter mode, false otherwise.
       */
      virtual bool isInFilterMode() {
          return false;
      }
      
      void checkFocus() {
          shared_ptr<T> adapter = getAdapter();
  //        const bool empty = adapter == NULL || adapter->getCount() == 0;
  //        const bool focusable = !empty || isInFilterMode();
  //        // The order in which we set focusable in touch mode/focusable may matter
  //        // for the client, see View::setFocusableInTouchMode() comments for more
  //        // details
  //        ViewGroup::setFocusableInTouchMode(focusable && mDesiredFocusableInTouchModeState);
  //        ViewGroup::setFocusable(focusable && mDesiredFocusableState);
          if (mEmptyView != NULL) {
              updateEmptyStatus((adapter == NULL) || adapter->isEmpty());
          }
      }
      
  private:
  
      /**
       * Update the status of the list based on the empty parameter.  If empty is true and
       * we have an empty view, display it.  In all the other cases, make sure that the listview
       * is VISIBLE and that the empty view is GONE (if it's not NULL).
       */
      void updateEmptyStatus(bool empty) {
          if (isInFilterMode()) {
              empty = false;
          }
          
          if (empty) {
              if (mEmptyView != NULL) {
                  mEmptyView->setVisibility(View::VISIBLE);
                  setVisibility(View::GONE);
              } else {
                  // If the caller just removed our empty view, make sure the list view is visible
                  setVisibility(View::VISIBLE);
              }
              
              // We are now GONE, so pending layouts will not be dispatched.
              // Force one here to make sure that the state of the list matches
              // the state of the adapter->
              if (mDataChanged) {
                  onLayout(false, mLeft, mTop, mRight, mBottom);
              }
          } else {
              if (mEmptyView != NULL) mEmptyView->setVisibility(View::GONE);
              setVisibility(View::VISIBLE);
          }
      }
      
      void selectionChanged() {
          if (mOnItemSelectedListener != NULL) {
              if (mInLayout || mBlockLayoutRequests) {
                  // If we are in a layout traversal, defer notification
                  // by posting. This ensures that the view tree is
                  // in a consistent state and is able to accomodate
                  // new layout or invalidate requests.
                  if (mSelectionNotifier == NULL) {
                      mSelectionNotifier = new SelectionNotifier(this);
                  }
                  post(mSelectionNotifier);
              } else {
                  fireOnSelected();
              }
          }
      }
      
      void fireOnSelected() {
          if (mOnItemSelectedListener == NULL) {
              return;
          }
          const int selection = getSelectedItemPosition();
          if (selection >= 0) {
              View *v = getSelectedView();
              mOnItemSelectedListener->onItemSelected(this, v, selection, getAdapter()->getItemId(selection));
          } else {
              mOnItemSelectedListener->onNothingSelected(this);
          }
      }
      
  protected:
      
      class AdapterDataSetObserver : public DataSetObserver {
          
      private:
          
  //        Parcelable *mInstanceState = NULL;
      
      public:
          
          AdapterDataSetObserver(AdapterView<T> *adapterView) {
              mAdapterView = adapterView;
          }
          
          virtual void onChanged() {
              mAdapterView->mDataChanged = true;
              mAdapterView->mOldItemCount = mAdapterView->mItemCount;
              shared_ptr<T> adapter = mAdapterView->getAdapter();
              mAdapterView->mItemCount = adapter->getCount();
              
              // Detect the case where a cursor that was previously invalidated has
              // been repopulated with new data.
              if (adapter->hasStableIds() &&
                  mAdapterView->mOldItemCount == 0 && mAdapterView->mItemCount > 0) {
  //                onRestoreInstanceState(mInstanceState);
              } else {
                  mAdapterView->rememberSyncState();
              }
              mAdapterView->checkFocus();
              mAdapterView->requestLayout();
          }
          
          virtual void onInvalidated() {
              mAdapterView->mDataChanged = true;
              shared_ptr<T> adapter = mAdapterView->getAdapter();
              
              if (adapter->hasStableIds()) {
                  // Remember the current state for the case where our hosting activity is being
                  // stopped and later restarted
  //                mInstanceState = mAdapterView->onSaveInstanceState();
              }
              
              // Data is invalid so we should reset our state
              mAdapterView->mOldItemCount = mAdapterView->mItemCount;
              mAdapterView->mItemCount = 0;
              mAdapterView->mSelectedPosition = INVALID_POSITION;
              mAdapterView->mSelectedRowId = INVALID_ROW_ID;
              mAdapterView->mNextSelectedPosition = INVALID_POSITION;
              mAdapterView->mNextSelectedRowId = INVALID_ROW_ID;
              mAdapterView->mNeedSync = false;
              
              mAdapterView->checkFocus();
              mAdapterView->requestLayout();
          }
          
          void clearSavedState() {
  //            mInstanceState = NULL;
          }
          
      private:
          AdapterView<T> *mAdapterView = NULL;
      };
      
      virtual void handleDataChanged() {
          const int count = mItemCount;
          bool found = false;
          
          if (count > 0) {
              
              int newPos;
              
              // Find the row we are supposed to sync to
              if (mNeedSync) {
                  // Update this first, since setNextSelectedPositionInt inspects
                  // it
                  mNeedSync = false;
                  
                  // See if we can find a position in the new data with the same
                  // id as the old selection
                  newPos = findSyncPosition();
                  if (newPos >= 0) {
                      // Verify that new selection is selectable
                      int selectablePos = lookForSelectablePosition(newPos, true);
                      if (selectablePos == newPos) {
                          // Same row id is selected
                          setNextSelectedPositionInt(newPos);
                          found = true;
                      }
                  }
              }
              if (!found) {
                  // Try to use the same position if we can't find matching data
                  newPos = getSelectedItemPosition();
                  
                  // Pin position to the available range
                  if (newPos >= count) {
                      newPos = count - 1;
                  }
                  if (newPos < 0) {
                      newPos = 0;
                  }
                  
                  // Make sure we select something selectable -- first look down
                  int selectablePos = lookForSelectablePosition(newPos, true);
                  if (selectablePos < 0) {
                      // Looking down didn't work -- try looking up
                      selectablePos = lookForSelectablePosition(newPos, false);
                  }
                  if (selectablePos >= 0) {
                      setNextSelectedPositionInt(selectablePos);
                      checkSelectionChanged();
                      found = true;
                  }
              }
          }
          if (!found) {
              // Nothing is selected
              mSelectedPosition = INVALID_POSITION;
              mSelectedRowId = INVALID_ROW_ID;
              mNextSelectedPosition = INVALID_POSITION;
              mNextSelectedRowId = INVALID_ROW_ID;
              mNeedSync = false;
              checkSelectionChanged();
          }
      }
      
      void checkSelectionChanged() {
          if ((mSelectedPosition != mOldSelectedPosition) || (mSelectedRowId != mOldSelectedRowId)) {
              selectionChanged();
              mOldSelectedPosition = mSelectedPosition;
              mOldSelectedRowId = mSelectedRowId;
          }
      }
      
      /**
       * Searches the adapter for a position matching mSyncRowId. The search starts at mSyncPosition
       * and then alternates between moving up and moving down until 1) we find the right position, or
       * 2) we run out of time, or 3) we have looked at every position
       *
       * @return Position of the row that matches mSyncRowId, or {@link #INVALID_POSITION} if it can't
       *         be found
       */
      int findSyncPosition() {
          int count = mItemCount;
          
          if (count == 0) {
              return INVALID_POSITION;
          }
          
          long idToMatch = mSyncRowId;
          int seed = mSyncPosition;
          
          // If there isn't a selection don't hunt for it
          if (idToMatch == INVALID_ROW_ID) {
              return INVALID_POSITION;
          }
          
          // Pin seed to reasonable values
          seed = std::max(0, seed);
          seed = std::min(count - 1, seed);
          
          uint64_t endTime = Clock::monotonicTime() + SYNC_MAX_DURATION_MILLIS;
          
          long rowId;
          
          // first position scanned so far
          int first = seed;
          
          // last position scanned so far
          int last = seed;
          
          // True if we should move down on the next iteration
          bool next = false;
          
          // True when we have looked at the first item in the data
          bool hitFirst;
          
          // True when we have looked at the last item in the data
          bool hitLast;
          
          // Get the item ID locally (instead of getItemIdAtPosition), so
          // we need the adapter
          shared_ptr<T> adapter = getAdapter();
          if (adapter == NULL) {
              return INVALID_POSITION;
          }
          
          while (Clock::monotonicTime() <= endTime) {
              rowId = adapter->getItemId(seed);
              if (rowId == idToMatch) {
                  // Found it!
                  return seed;
              }
              
              hitLast = last == count - 1;
              hitFirst = first == 0;
              
              if (hitLast && hitFirst) {
                  // Looked at everything
                  break;
              }
              
              if (hitFirst || (next && !hitLast)) {
                  // Either we hit the top, or we are trying to move down
                  last++;
                  seed = last;
                  // Try going up next time
                  next = false;
              } else if (hitLast || (!next && !hitFirst)) {
                  // Either we hit the bottom, or we are trying to move up
                  first--;
                  seed = first;
                  // Try going down next time
                  next = true;
              }
              
          }
          
          return INVALID_POSITION;
      }
  
      /**
       * Find a position that can be selected (i.e., is not a separator).
       *
       * @param position The starting position to look at.
       * @param lookDown Whether to look down for other positions.
       * @return The next selectable position starting at position and then searching either up or
       *         down. Returns {@link #INVALID_POSITION} if nothing can be found.
       */
      virtual int lookForSelectablePosition(int position, bool lookDown) {
          return position;
      }
      
      /**
       * Utility to keep mSelectedPosition and mSelectedRowId in sync
       * @param position Our current position
       */
      void setSelectedPositionInt(int position) {
          mSelectedPosition = position;
          mSelectedRowId = getItemIdAtPosition(position);
      }
      
      /**
       * Utility to keep mNextSelectedPosition and mNextSelectedRowId in sync
       * @param position Intended value for mSelectedPosition the next time we go
       * through layout
       */
      void setNextSelectedPositionInt(int position) {
          mNextSelectedPosition = position;
          mNextSelectedRowId = getItemIdAtPosition(position);
          // If we are trying to sync to the selection, update that too
          if (mNeedSync && mSyncMode == SYNC_SELECTED_POSITION && position >= 0) {
              mSyncPosition = position;
              mSyncRowId = mNextSelectedRowId;
          }
      }
      
      /**
       * Remember enough information to restore the screen state when the data has
       * changed.
       *
       */
      void rememberSyncState() {
          if (getChildCount() > 0) {
              mNeedSync = true;
              mSyncHeight = mLayoutHeight;
              if (mSelectedPosition >= 0) {
                  // Sync the selection state
                  shared_ptr<View> v = getChildAt(mSelectedPosition - mFirstPosition);
                  mSyncRowId = mNextSelectedRowId;
                  mSyncPosition = mNextSelectedPosition;
                  if (v != NULL) {
                      mSpecificTop = v->getTop();
                  }
                  mSyncMode = SYNC_SELECTED_POSITION;
              } else {
                  // Sync the based on the offset of the first view
                  shared_ptr<View> v = getChildAt(0);
                  shared_ptr<T> adapter = getAdapter();
                  if (mFirstPosition >= 0 && mFirstPosition < adapter->getCount()) {
                      mSyncRowId = adapter->getItemId(mFirstPosition);
                  } else {
                      mSyncRowId = NO_ID_INT;
                  }
                  mSyncPosition = mFirstPosition;
                  if (v != NULL) {
                      mSpecificTop = v->getTop();
                  }
                  mSyncMode = SYNC_FIRST_POSITION;
              }
          }
      }
      
      virtual void onLayout(bool changed, int left, int top, int right, int bottom) {
          mLayoutHeight = getHeight();
      }
      
      /**
       * Override to prevent freezing of any views created by the adapter->
       */
  //    virtual void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
  //        dispatchFreezeSelfOnly(container);
  //    }
      
      /**
       * Override to prevent thawing of any views created by the adapter->
       */
  //    virtual void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
  //        dispatchThawSelfOnly(container);
  //    }
      
      virtual void onDetachedFromWindow() {
          ViewGroup::onDetachedFromWindow();
          removeCallbacks(mSelectionNotifier);
      }
      
      bool isScrollableForAccessibility() {
          shared_ptr<T> adapter = getAdapter();
          if (adapter != NULL) {
              const int itemCount = adapter->getCount();
              return itemCount > 0
              && (getFirstVisiblePosition() > 0 || getLastVisiblePosition() < itemCount - 1);
          }
          return false;
      }
      
      virtual bool canAnimate() {
          return /* ViewGroup::canAnimate() && */ mItemCount > 0;
      }
  };
  
  ANDROID_END
  
  #endif /* defined(__cocos2dx__AdapterView__) */
  