Skip to content

Instantly share code, notes, and snippets.

@Palisand
Last active October 8, 2017 21:28
Show Gist options
  • Save Palisand/5519ab23bd8aef910e138fb3c1740d52 to your computer and use it in GitHub Desktop.
Save Palisand/5519ab23bd8aef910e138fb3c1740d52 to your computer and use it in GitHub Desktop.
Changes for scroll-to-cursor functionality.
import android.text.Layout;
...
private class ReactSelectionWatcher implements SelectionWatcher {
private ReactEditText mReactEditText;
private EventDispatcher mEventDispatcher;
private int mPreviousSelectionStart;
private int mPreviousSelectionEnd;
public ReactSelectionWatcher(ReactEditText editText) {
mReactEditText = editText;
ReactContext reactContext = (ReactContext) editText.getContext();
mEventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher();
}
@Override
public void onSelectionChanged(int start, int end) {
/* >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> */
// Calculate cursor position
// Credit: yuku
// https://stackoverflow.com/questions/5044342/how-to-get-cursor-position-x-y-in-edittext-android
Layout layout = mReactEditText.getLayout();
int line = layout.getLineForOffset(start);
int baseline = layout.getLineBaseline(line);
int ascent = layout.getLineAscent(line);
float cursorPositionX = layout.getPrimaryHorizontal(start);
float cursorPositionY = baseline + ascent;
/* <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< */
// Android will call us back for both the SELECTION_START span and SELECTION_END span in text
// To prevent double calling back into js we cache the result of the previous call and only
// forward it on if we have new values
if (mPreviousSelectionStart != start || mPreviousSelectionEnd != end) {
mEventDispatcher.dispatchEvent(
new ReactTextInputSelectionEvent(
mReactEditText.getId(),
start,
end,
/* >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> */
PixelUtil.toDIPFromPixel(cursorPositionX),
PixelUtil.toDIPFromPixel(cursorPositionY)
/* <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< */
));
mPreviousSelectionStart = start;
mPreviousSelectionEnd = end;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment