Last active
October 8, 2017 21:28
-
-
Save Palisand/5519ab23bd8aef910e138fb3c1740d52 to your computer and use it in GitHub Desktop.
Changes for scroll-to-cursor functionality.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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