use*_*820 7 android text cursor android-edittext
我是 android 编程的新手。我添加了一个上下文菜单来编辑文本。我希望我可以在长按光标下找到单词。请帮忙。我可以通过以下代码获取选定的文本。
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
EditText edittext = (EditText)findViewById(R.id.editText1);
menu.setHeaderTitle(edittext.getText().toString().substring(edittext.getSelectionStart(), edittext.getSelectionEnd()));
menu.add("Copy");
}
Run Code Online (Sandbox Code Playgroud)
edittext 有一些文本,例如“一些文本。一些更多的文本”。用户单击“更多”,因此光标将位于“更多”一词中的某个位置。我希望当用户长按这个词时,我可以在光标下得到“更多”等词。
有更好更简单的解决方案:在android中使用模式
public String getCurrentWord(EditText editText) {
Spannable textSpan = editText.getText();
final int selection = editText.getSelectionStart();
final Pattern pattern = Pattern.compile("\\w+");
final Matcher matcher = pattern.matcher(textSpan);
int start = 0;
int end = 0;
String currentWord = "";
while (matcher.find()) {
start = matcher.start();
end = matcher.end();
if (start <= selection && selection <= end) {
currentWord = textSpan.subSequence(start, end).toString();
break;
}
}
return currentWord; // This is current word
}
Run Code Online (Sandbox Code Playgroud)
EditText et = (EditText) findViewById(R.id.xx);
int startSelection = et.getSelectionStart();
String selectedWord = "";
int length = 0;
for(String currentWord : et.getText().toString().split(" ")) {
System.out.println(currentWord);
length = length + currentWord.length() + 1;
if(length > startSelection) {
selectedWord = currentWord;
break;
}
}
System.out.println("Selected word is: " + selectedWord);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6010 次 |
| 最近记录: |