244

There are two EditText,while loading the page a text is set in the first EditText, So now cursor will be in the starting place of EditText, I want to set cursor position in the second EditText which contains no data. How to do this?

Bhavik Kamdar
  • 301
  • 1
  • 7
  • 15
nila
  • 2,983
  • 4
  • 16
  • 15
  • 2
    you can set its gravity to 'center'.it will automatically sets the cursor to be in center. your text would also be centered then. – Hiral Vadodaria Nov 07 '11 at 10:27
  • first of all, try improving your accept ratio. second, what do you mean by setting cursor position, when there is no text in edittext? – Vladimir Nov 07 '11 at 10:28

23 Answers23

506

Where position is an int:

editText1.setSelection(position)
NotACleverMan
  • 11,347
  • 11
  • 42
  • 64
100

I have done this way to set cursor position to end of the text after updating the text of EditText programmatically here, etmsg is EditText

etmsg.setText("Updated Text From another Activity");
int position = etmsg.length();
Editable etext = etmsg.getText();
Selection.setSelection(etext, position);
MKJParekh
  • 32,883
  • 11
  • 84
  • 97
41

How to Set EditText Cursor position in Android

Below Code is Set cursor to Starting in EditText:

 EditText editText = (EditText)findViewById(R.id.edittext_id);
 editText.setSelection(0);

Below Code is Set cursor to end of the EditText:

EditText editText = (EditText)findViewById(R.id.edittext_id);
editText.setSelection(editText.getText().length());

Below Code is Set cursor after some 2th Character position :

 EditText editText = (EditText)findViewById(R.id.edittext_id);
 editText.setSelection(2);
IntelliJ Amiya
  • 70,230
  • 14
  • 154
  • 181
18

I want to set cursor position in edittext which contains no data

There is only one position in an empty EditText, it's setSelection(0).

Or did you mean you want to get focus to your EditText when your activity opens? In that case its requestFocus()

Michael
  • 8,464
  • 2
  • 59
  • 62
Reno
  • 32,851
  • 11
  • 85
  • 99
  • setSelection(0) is not working ,I dont want to get focus to the second EditText,I only want to set the cursor in the second EditText – nila Nov 07 '11 at 12:47
  • 3
    If I remember correctly, when an EditText requests focus, the cursor is set. [Read this](http://plainoldstan.blogspot.com/2010/09/android-set-focus-and-show-soft.html) – Reno Nov 08 '11 at 06:51
12

use the below line

e2.setSelection(e2.length());

e2 is edit text Object Name

piet.t
  • 11,035
  • 20
  • 40
  • 49
Syed Danish Haider
  • 1,126
  • 9
  • 14
10

Let editText2 is your second EditText view .then put following piece of code in onResume()

editText2.setFocusableInTouchMode(true);
editText2.requestFocus();

or put

<requestFocus />

in your xml layout of the second EditText view.

monish george
  • 741
  • 6
  • 14
10

If you want to place the cursor in a certain position on an EditText, you can use:

yourEditText.setSelection(position);

Additionally, there is the possibility to set the initial and final position, so that you programmatically select some text, this way:

yourEditText.setSelection(startPosition, endPosition);

Please note that setting the selection might be tricky since you can place the cursor before or after a character, the image below explains how to index works in this case:

enter image description here

So, if you want the cursor at the end of the text, just set it to yourEditText.length().

Junior Damacena
  • 121
  • 1
  • 6
7

some time edit text cursor donot comes at particular position is if we directly use editText.setSelection(position); . In that case you can try

editText.post(new Runnable() {
                @Override
                public void run() {
                    editText.setSelection(string.length());
                }
            });
Sourabh soni
  • 430
  • 5
  • 9
5

setSelection(int index) method in Edittext should allow you to do this.

Ravindra Kushwaha
  • 6,734
  • 9
  • 42
  • 85
Avinash
  • 759
  • 1
  • 8
  • 16
4

as a reminder: if you are using edittext.setSelection() to set the cursor, and it is NOT working while setting up an alertdialog for example, make sure to set the selection() AFTER the dialog has been created

example:

AlertDialog dialog = builder.show();
input.setSelection(x,y);
Padma Kumar
  • 20,420
  • 16
  • 69
  • 127
calav3ra
  • 196
  • 1
  • 9
3

This code will help you to show your cursor at the last position of editing text.

 editText.requestFocus();
 editText.setSelection(editText.length());
Anton Yuriev
  • 382
  • 4
  • 8
Kailas Bhakade
  • 1,812
  • 20
  • 26
2

Remember call requestFocus() before setSelection for edittext.

Vinoth Krishnan
  • 2,849
  • 6
  • 25
  • 33
Dong Thang
  • 334
  • 3
  • 5
1

I won't get setSelection() method directly , so i done like below and work like charm

EditText editText = (EditText)findViewById(R.id.edittext_id);
editText.setText("Updated New Text");
int position = editText.getText().length();
Editable editObj= editText.getText();
Selection.setSelection(editObj, position);
sujith s
  • 716
  • 10
  • 18
1

If you want to set the cursor after n character from right to left then you have to do like this.

edittext.setSelection(edittext.length()-n);

If edittext's text like

version<sub></sub>

and you want to move cursor at 6th position from right

Then it will move the cursor at-

    version<sub> </sub>
                ^
Rasel
  • 4,555
  • 3
  • 26
  • 35
1
EditText editText = findViewById(R.id.editText);
editText.setSelection(editText.getText().length());
Satendra Behre
  • 149
  • 1
  • 6
1
if(myEditText.isSelected){
    myEditText.setSelection(myEditText.length())
    }
MSilva
  • 81
  • 6
1

You can use like this:

if (your_edittext.getText().length() > 0 ) {

    your_edittext.setSelection(your_edittext.getText().length());
}

Can you add this line to your EditText xml

android:gravity="right"
android:ellipsize="end"
android:paddingLeft="10dp"//you set this as you need

But when any Text writing you should set the paddingleft to zero

you should use this on addTextChangedListener

SamiunNafis
  • 101
  • 2
  • 5
0

Set cursor to a row and column

You can use the following code to get the position in your EditText that corresponds to a certain row and column. You can then use editText.setSelection(getIndexFromPos(row, column)) to set the cursor position. The following calls to the method can be made:

  • getIndexFromPos(x, y) Go to the column y of line x
  • getIndexFromPos(x, -1) Go to the last column of line x
  • getIndexFromPos(-1, y) Go to the column y of last line
  • getIndexFromPos(-1, -1) Go to the last column of the last line

All line and column bounds are handled; Entering a column greater than the line's length will return position at the last column of the line. Entering a line greater than the EditText's line count will go to the last line. It should be reliable enough as it was heavily tested.

static final String LINE_SEPARATOR = System.getProperty("line.separator");

int getIndexFromPos(int line, int column) {
    int lineCount = getTrueLineCount();
    if (line < 0) line = getLayout().getLineForOffset(getSelectionStart());  // No line, take current line
    if (line >= lineCount) line = lineCount - 1;  // Line out of bounds, take last line

    String content = getText().toString() + LINE_SEPARATOR;
    int currentLine = 0;
    for (int i = 0; i < content.length(); i++) {
        if (currentLine == line) {
            int lineLength = content.substring(i, content.length()).indexOf(LINE_SEPARATOR);
            if (column < 0 || column > lineLength) return i + lineLength;  // No column or column out of bounds, take last column
            else return i + column;
        }
        if (String.valueOf(content.charAt(i)).equals(LINE_SEPARATOR)) currentLine++;
    }
    return -1;  // Should not happen
}

// Fast alternative to StringUtils.countMatches(getText().toString(), LINE_SEPARATOR) + 1
public int getTrueLineCount() {
    int count;
    String text = getText().toString();
    StringReader sr = new StringReader(text);
    LineNumberReader lnr = new LineNumberReader(sr);
    try {
        lnr.skip(Long.MAX_VALUE);
        count = lnr.getLineNumber() + 1;
    } catch (IOException e) {
        count = 0;  // Should not happen
    }
    sr.close();
    return count;
}

The question was already answered but I thought someone could want to do that instead.

It works by looping through each character, incrementing the line count every time it finds a line separator. When the line count equals the desired line, it returns the current index + the column, or the line end index if column is out of bounds. You can also reuse the getTrueLineCount() method, it returns a line count ignoring text wrapping, unlike TextView.getLineCount().

Nicolas
  • 5,182
  • 2
  • 22
  • 58
  • This code seems very useful for multilineEditText developers, but I couldn't apply this code. You mentioned x and y but defined line and column, though, editText.setSelection(getIndexFromPos(getTrueLineCount(), getTrueLineCount())); this seems not working and not calling the function. So, how can we use your code? – Bay Jan 13 '21 at 20:26
  • @Bay It's been a long time since I've written this answer, and I had just begun android development at the time. But the principle seems simple enough that you should be able to debug the code – Nicolas Jan 13 '21 at 20:34
0

In kotlin, you could create an extension function like this:

fun EditText.placeCursorAtLast() {
    val string = this.text.toString()
    this.setSelection(string.length)
}

and then simply call myEditText.placeCursorAtLast()

notdrone
  • 1,654
  • 13
  • 11
0

If you want to set cursor position in EditText? try these below code

EditText rename;
 String title = "title_goes_here";
 int counts = (int) title.length();
 rename.setSelection(counts);
 rename.setText(title);
Mujahid Khan
  • 925
  • 1
  • 12
  • 19
0

How to resolve the cursor position issue which is automatically moving to the last position after formatting in US Mobile like (xxx) xxx-xxxx in Android.

private String oldText = "";
private int lastCursor;
private EditText mEtPhone;

@Override
    public void afterTextChanged(Editable s) {
String cleanString = AppUtil.cleanPhone(s.toString());

String format = cleanString.length() < 11 ? cleanString.replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1) $2-$3") :
                cleanString.substring(0, 10).replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1) $2-$3");


boolean isDeleted = format.length() < oldText.length();

        try {

            int cur = AppUtil.getPointer(lastCursor, isDeleted ? s.toString() : format, oldText, isDeleted);
            mEtPhone.setSelection(cur > 0 ? cur : format.length());

        }catch (Exception e){
            e.printStackTrace();
            mEtPhone.setSelection(format.length());
        }

        mEtPhone.addTextChangedListener(this);

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        oldText = s.toString();
        lastCursor = start;
    }

Define the below method to any Activityclass in my case Activity name is AppUtil and access it globally

public static int getPointer(int index, String newString, String oldText, boolean isDeleted){

        int diff = Math.abs(newString.length() - oldText.length());

        return diff > 1 ? isDeleted ? index - diff : index  + diff : isDeleted ? index : index + 1;
    }

public static String cleanPhone(String phone){

        if(TextUtils.isEmpty(phone))
            return "";

        StringBuilder sb = new StringBuilder();
        for(char c : phone.toCharArray()){
            if(Character.isDigit(c))
                sb.append(c);
        }
        return sb.toString();
    }

And if you want to set any specific position

edittext.setSelection(position);
jtate
  • 2,155
  • 6
  • 24
  • 31
0

I'm so late to answer this problem, so I figure it out. Just use,

android:gravity="center_horizontal"
Jack
  • 128
  • 9
-4

I believe the most simple way to do this is just use padding.

Say in your xml's edittext section, add android:paddingLeft="100dp" This will move your start position of cursor 100dp right from left end.

Same way, you can use android:paddingRight="100dp" This will move your end position of cursor 100dp left from right end.

For more detail, check this article on my blog: Android: Setting Cursor Starting and Ending Position in EditText Widget

Andrew Barber
  • 37,547
  • 20
  • 91
  • 118
Arthur Wang
  • 2,955
  • 4
  • 19
  • 25
  • 2
    Padding has nothing to do with cursor position, and is a completely wrong school of thought in this particular situation. – Shark Aug 28 '15 at 15:20