Java 有没有办法在TextView中自动选择文本?
有没有办法在TextView上自动选择或突出显示预定的文本区域?例如,我希望在启动活动时,文本视图上的特定行已经被预先选择,而不是让用户自己选择该文本区域。您要查找的很可能是setSelection函数 它的工作原理如下:Java 有没有办法在TextView中自动选择文本?,java,android,android-studio,Java,Android,Android Studio,有没有办法在TextView上自动选择或突出显示预定的文本区域?例如,我希望在启动活动时,文本视图上的特定行已经被预先选择,而不是让用户自己选择该文本区域。您要查找的很可能是setSelection函数 它的工作原理如下: EditText edText = findViewById(id); edText.setSelection(start, stop); setSelection()函数接受两个参数start和stop,这两个参数都是int,它是要开始选择的字符的索引,也是要结束选择的字
EditText edText = findViewById(id);
edText.setSelection(start, stop);
setSelection()
函数接受两个参数start和stop,这两个参数都是int,它是要开始选择的字符的索引,也是要结束选择的字符的索引。
例如,setSelection(0,1)
将选择编辑文本的第一个字符
如果要在EditText中选择特定字符串,可以执行以下操作:
EditText edText = findViewById(id);
String lookingFor = "whatever youre looking for";
//You get the index of the first character of the string you're looking for
int start = edText.getText().toString().indexOf(lookingFor);
//You add the string's length to the index so the selection actually selects the
//whole string.
int stop = start+lookingFor.length();
//You -start- selecting from the 1st character and -stop- at the last character
//Of the string you're looking for.
edText.setSelection(start,stop);
是否有一个版本的可用于TextView而不是EditText?@a遗憾的是,没有,您需要为此创建自己的自定义类。如果您想在此处实现该类,已经有一个答案: