Set cursor position in android Edit text-ThrowExceptions

Exception or error:

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"
How to solve:

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);

###

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);

###

Try this

editText1.requestFocus(Your_Text.length());

Hope it will help you.

###

editText1.setSelection(Your position)

or

EditText etext = (EditText)findViewById(R.id.inbox);
etext.setSelection(etext.getText().length());

Leave a Reply

Your email address will not be published. Required fields are marked *