Search code examples
androidscrollaccessibilityandroid-cursoradapter

Get current letter onScroll?


I'm building an accessibility app and want to read out loud the current letter on the AlphabetIndexer as the user scrolls.

How can I run some code onScroll? And how do I get the current letter inside the CursorAdapter?

Thanks


This is what I'm trying (I tried to leave only the relevant bits):

private class ContactsAdapter extends CursorAdapter implements SectionIndexer {
    private LayoutInflater mInflater;
    private AlphabetIndexer mAlphabetIndexer;

    public ContactsAdapter(Context context) {
        super(context, null, 0);
        mInflater = LayoutInflater.from(context);
        final String alphabet = context.getString(R.string.alphabet);
        mAlphabetIndexer = new AlphabetIndexer(null, ContactsQuery.SORT_KEY, alphabet);
    }

    // ...

    @Override
    public Object[] getSections() {
        return mAlphabetIndexer.getSections();
    }

    @Override
    public int getPositionForSection(int i) {
        if (getCursor() == null) {
            return 0;
        }
        Log.i("TAG", "getPositionForSection " + mAlphabetIndexer.getPositionForSection(i));
        return mAlphabetIndexer.getPositionForSection(i);
    }

    @Override
    public int getSectionForPosition(int i) {
        if (getCursor() == null) {
            return 0;
        }
        return mAlphabetIndexer.getSectionForPosition(i);
    }
}

Solution

  • SectionIndexer.getSectionForPosition is going to return the index of the corresponding section within SectionIndexer.getSections. So to retrieve the current letter for a section, all you need to do is call:

        @Override
        public int getSectionForPosition(int i) {
            if (getCursor() == null) {
                return 0;
            }
            // Prints the letter for the current section
            System.out.println(getSections()[mAlphabetIndexer.getSectionForPosition(i)]);
            return mAlphabetIndexer.getSectionForPosition(i);
        }