How to set cursor position in EditText?

2019-01-07 04:54发布

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?

20条回答
虎瘦雄心在
2楼-- · 2019-01-07 05:19

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

查看更多
ら.Afraid
3楼-- · 2019-01-07 05:20

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

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

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

查看更多
太酷不给撩
4楼-- · 2019-01-07 05:20

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

查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-01-07 05:21

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);
查看更多
地球回转人心会变
6楼-- · 2019-01-07 05:21

In Xml file android:paddingLeft:

<EditText
    android:id="@+id/txt_amount"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="10dp"/>

i hope this help you

查看更多
趁早两清
7楼-- · 2019-01-07 05:24

Where position is an int:

editText1.setSelection(position)
查看更多
登录 后发表回答