Skip to content

Instantly share code, notes, and snippets.

@ryjen
Last active June 29, 2020 07:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryjen/e63502afe677f00007e9 to your computer and use it in GitHub Desktop.
Save ryjen/e63502afe677f00007e9 to your computer and use it in GitHub Desktop.
Android: How to get the correct CursorAdapter position inside a MergeAdapter (cwac.commonsware.com)
/**
* gets [section,item idx in section] for raw list position
*
* @param adapter
* @param position: raw position in {@link com.commonsware.cwac.merge.MergeAdapter}
* @return ArrayList<Integer>
*/
public static Pair<Integer, Integer> getMergeAdapterPos(MergeAdapter adapter, int
position) {
int section = -1;
int sectionStart = -1;
for (int i = 0; i <= position; i++) {
if (!(adapter.getItem(i) instanceof Cursor)) {
sectionStart = i;
section++;
}
}
int correctedPos = position - sectionStart - 1;
return new Pair<Integer, Integer>(section, correctedPos);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
Adapter adapter = mergeAdapter.getAdapter(position);
if (adapter instanceof CursorAdapter) {
CursorAdapter cursorAdapter = (CursorAdapter) adapter;
Pair<Integer, Integer> realPosition = getMergeAdapterPos(mergeAdapter, position);
cursorAdapter.getCursor().moveToPosition(realPosition.second);
String rowId = cursorAdapter.getCursor().getString(cursorAdapter.getCursor().getColumnIndex("_id"));
// do other stuff
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment