How to set cursor position in EditText?

前端 未结 23 1491
广开言路
广开言路 2020-11-28 02:51

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

相关标签:
23条回答
  • 2020-11-28 03:30

    Where position is an int:

    editText1.setSelection(position)
    
    0 讨论(0)
  • 2020-11-28 03:33

    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);
    
    0 讨论(0)
  • 2020-11-28 03:34

    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.

    0 讨论(0)
  • 2020-11-28 03:34

    Remember call requestFocus() before setSelection for edittext.

    0 讨论(0)
  • 2020-11-28 03:34

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

    0 讨论(0)
提交回复
热议问题