From cb5e2d59c3eec1957606d65783c4e1c8479df422 Mon Sep 17 00:00:00 2001 From: Vincent Yang Date: Mon, 20 Jul 2015 17:50:02 +0800 Subject: [PATCH] Fixed #9382 : ui::ListView->getCurSelectedIndex() is out of range. --- cocos/ui/UIListView.cpp | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/cocos/ui/UIListView.cpp b/cocos/ui/UIListView.cpp index d127585303..6f685c8b06 100644 --- a/cocos/ui/UIListView.cpp +++ b/cocos/ui/UIListView.cpp @@ -35,7 +35,7 @@ ListView::ListView(): _model(nullptr), _gravity(Gravity::CENTER_VERTICAL), _itemsMargin(0.0f), -_curSelectedIndex(0), +_curSelectedIndex(-1), _refreshViewDirty(true), _listViewEventListener(nullptr), _listViewEventSelector(nullptr), @@ -230,14 +230,7 @@ void ListView::insertDefaultItem(ssize_t index) { return; } - Widget* newItem = _model->clone(); - - _items.insert(index, newItem); - ScrollView::addChild(newItem); - - remedyLayoutParameter(newItem); - - _refreshViewDirty = true; + insertCustomItem(_model->clone(), index); } @@ -285,6 +278,18 @@ void ListView::removeChild(cocos2d::Node *child, bool cleaup) Widget* widget = dynamic_cast(child); if (nullptr != widget) { + if (-1 != _curSelectedIndex) + { + auto removedIndex = getIndex(widget); + if (_curSelectedIndex > removedIndex) + { + _curSelectedIndex -= 1; + } + else if (_curSelectedIndex == removedIndex) + { + _curSelectedIndex = -1; + } + } _items.eraseObject(widget); } @@ -300,10 +305,18 @@ void ListView::removeAllChildrenWithCleanup(bool cleanup) { ScrollView::removeAllChildrenWithCleanup(cleanup); _items.clear(); + _curSelectedIndex = -1; } void ListView::insertCustomItem(Widget* item, ssize_t index) { + if (-1 != _curSelectedIndex) + { + if (_curSelectedIndex >= index) + { + _curSelectedIndex += 1; + } + } _items.insert(index, item); ScrollView::addChild(item);