Set cursor position in android Edit text [duplicat

2019-02-05 23:20发布

问题:

This question already has an answer here:

  • Android EditText how to start cursor pointer at the end of all characters- not end of first line 2 answers

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"

回答1:

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


回答2:

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


回答3:

Try this

editText1.requestFocus(Your_Text.length());

Hope it will help you.



回答4:

editText1.setSelection(Your position)

or

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