在当前光标位置上从EditText获取单词 [英] Get word from EditText on current cursor position

查看:192
本文介绍了在当前光标位置上从EditText获取单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是android编程的新手.我在编辑文本中添加了上下文菜单.我希望我能长按鼠标下的单词.请帮忙.我可以通过以下代码获取选定的文本.

I am new to android programing. I added a context menu to edittext. I wish I can get word under cursor on long press. Help Please. I can get selected text by following code.

@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");
}

edittext有一些文本,例如一些文本.更多文本".用户单击更多",因此光标将在单词更多"中的某些位置.我希望当用户长按单词时,我可以在光标下得到单词"more",等等.

edittext have some text e.g "Some text. Some more text". User clicked on "more" so the cursor will be in some where in the word "more". I want when user long press the word I can get the word "more" and so on other words under the cursor.

推荐答案

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

这篇关于在当前光标位置上从EditText获取单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆