Skip to content

Commit 1656394

Browse files
QichenZhucipolleschi
authored andcommittedFeb 6, 2025
Set TextInput selection correctly when attached to window in Android (#46948)
Summary: On Android, when `ReactEditText` is attached to window, `setTextIsSelectable` moves the caret to the beginning, so we need to restore the selection. This is similar to what we did in #17851. Fixes #46943 ## Changelog: [ANDROID] [FIXED] - Fix TextInput caret moving to the beginning when attached to window Pull Request resolved: #46948 Test Plan: Code to reproduce in RNTester: ```TSX import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import {TextInput} from 'react-native'; import {useEffect, useRef} from 'react'; function Playground() { const input = useRef(null); useEffect(() => { setTimeout(() => input.current?.focus(), 1000); }, []); return <TextInput ref={input} value='1.00' selection={{start: 4, end: 4}} />; } export default ({ title: 'Playground', name: 'playground', render: (): React.Node => <Playground />, }: RNTesterModuleExample); ``` Before | After -- | -- ![Screenshot_1728553990](https://github.com/user-attachments/assets/382cf3ec-7437-4b0d-8c15-c8923d677afd) | ![Screenshot_1728553884](https://github.com/user-attachments/assets/9883e966-e9b8-4f8a-bedb-6ee43880d482) Reviewed By: cortinico Differential Revision: D64175774 Pulled By: rshest fbshipit-source-id: ef9fdbecca582c8075bcdfd2d9b810b04d87e3d9
1 parent 4475e01 commit 1656394

File tree

1 file changed

+6
-0
lines changed
  • packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/textinput

1 file changed

+6
-0
lines changed
 

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1035,12 +1035,18 @@ public void onStartTemporaryDetach() {
10351035
public void onAttachedToWindow() {
10361036
super.onAttachedToWindow();
10371037

1038+
int selectionStart = getSelectionStart();
1039+
int selectionEnd = getSelectionEnd();
1040+
10381041
// Used to ensure that text is selectable inside of removeClippedSubviews
10391042
// See https://github.com/facebook/react-native/issues/6805 for original
10401043
// fix that was ported to here.
10411044

10421045
super.setTextIsSelectable(true);
10431046

1047+
// Restore the selection since `setTextIsSelectable` changed it.
1048+
setSelection(selectionStart, selectionEnd);
1049+
10441050
if (mContainsImages) {
10451051
Spanned text = getText();
10461052
TextInlineImageSpan[] spans = text.getSpans(0, text.length(), TextInlineImageSpan.class);

0 commit comments

Comments
 (0)
Please sign in to comment.