在android编辑文本中设置光标位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20838227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:34:32  来源:igfitidea点击:

Set cursor position in android Edit text

androidandroid-edittext

提问by Hassaan Rabbani

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?

如何在android编辑文本中设置光标位置?我有一个编辑文本,在创建时我想将光标设置为文本中间的某些时间,我该怎么办?

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"

回答by Hassaan Rabbani

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

回答by Jagadesh Seeram

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

回答by Sanket Shah

Try this

尝试这个

editText1.requestFocus(Your_Text.length());

Hope it will help you.

希望它会帮助你。

回答by codercat

editText1.setSelection(Your position)

or

或者

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