23

How can i set the cursor position in android edit text? I have an edit text and on create i want to set the cursor to some times in the end some times in the middle of the text, what can i do?

my edit text is as follows:

android:id="@+id/editText11"
android:layout_width="wrap_content"
android:layout_height="200sp"
android:layout_above="@+id/horizontalScrollView1"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="top"
android:background="#00000000"
android:inputType="textMultiLine"
android:singleLine="true"

4 Answers4

50

You can achieve this by using :

Edittext.setSelection(Edittext.length());

this will put the cursor position in the end. otherwise you can get the text in a string and check the text position where you want to put the cursor and do it like this

String text = edittext.getText().toString();

for(int i = 0; i <text.length();i++)
{
//your logic here to check the position of text
}

and then

Edittext.setSelection(position);
Rajesh Satvara
  • 3,842
  • 2
  • 30
  • 50
Hassaan Rabbani
  • 2,469
  • 5
  • 30
  • 55
19

Position at the start

editText.setSelection(0);

Position at the end

editText.setSelection(editText.getText().length());

Position at the middle

editText.setSelection(editText.getText().length() / 2);
Jagadesh Seeram
  • 2,630
  • 1
  • 16
  • 29
4

Try this

editText1.requestFocus(Your_Text.length());

Hope it will help you.

Sanket Shah
  • 4,352
  • 3
  • 21
  • 41
  • The method you mentioned takes in direction and not length. Check [this](https://developer.android.com/reference/android/view/View#requestfocus) out – Shaishav Apr 27 '18 at 08:27
1
editText1.setSelection(Your position)

or

EditText etext = (EditText)findViewById(R.id.inbox);
etext.setSelection(etext.getText().length());
codercat
  • 22,873
  • 9
  • 61
  • 85