Nothing about this problem (the problem of getting the ListView selected item index) is particular to, nor should be accomplished by, use of the accessibility apis.
Documentation for the "getToIndex()" function:
Gets the index of text selection end or the index of the last visible item when scrolling.
It seems from your clarification and your code, namely this line:
event.getEventType() == AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED)
That what you're really looking for is the view that just received ACCESSIBILITY_FOCUS, and NOT the view that is "selected". These are very different. I would definitely recommend changing this
int selectedItemPosition = ...
To
int a11yFocusedItemPosition = ...
Which is MUCH more clear. "Selected" means something very specific in terms of list views, and this is confusing things. Assuming Accessibility Focus is in fact the thing that you're looking for, this should do nicely:
listView.setAccessibilityDelegate(new View.AccessibilityDelegate() {
@Override
public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED) {
int accessibilityFocusedItemIndex = -1;
for (int i = 0; i < host.getChildCount(); i++) {
if (host.getChildAt(i) == child) {
accessibilityFocusedItemIndex = i;
break;
}
}
Log.d("LogTag", "Accessibility Focused Item Index: " + accessibilityFocusedItemIndex);
}
return super.onRequestSendAccessibilityEvent(host, child, event);
}
});
Note that list view is a special case where a function like this manages to work, because the focusable child is usually a direct descendant of the host view. This may not be true for individual active elements not wrapped within the list view cell.