Android 从TextView获取所选文本
我正在尝试获取用户在文本视图中选择的文本, 我不想使用android:textIsSelectable=“true”来允许我的用户复制/粘贴操作Android 从TextView获取所选文本,android,textview,Android,Textview,我正在尝试获取用户在文本视图中选择的文本, 我不想使用android:textIsSelectable=“true”来允许我的用户复制/粘贴操作 但是,我不知道如何在显示操作栏菜单后获取文本,目标是实现一种类似Google book的行为:你选择一个单词,它会给出一个定义。我想你要找的是TextView.setCustomSelectionActionModeCallback。这将允许您在选择文本时创建自己的ActionMode.Callback。然后,您可以使用TextView.getSele
但是,我不知道如何在显示操作栏菜单后获取文本,目标是实现一种类似Google book的行为:你选择一个单词,它会给出一个定义。我想你要找的是
TextView.setCustomSelectionActionModeCallback
。这将允许您在选择文本时创建自己的ActionMode.Callback
。然后,您可以使用TextView.getSelectionStart
和TextView.getSelectionEnd
在选择菜单项时检索所选文本。下面是一个简单的例子:
mTextView.setCustomSelectionActionModeCallback(new Callback() {
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// Remove the "select all" option
menu.removeItem(android.R.id.selectAll);
// Remove the "cut" option
menu.removeItem(android.R.id.cut);
// Remove the "copy all" option
menu.removeItem(android.R.id.copy);
return true;
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Called when action mode is first created. The menu supplied
// will be used to generate action buttons for the action mode
// Here is an example MenuItem
menu.add(0, DEFINITION, 0, "Definition").setIcon(R.drawable.ic_action_book);
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
// Called when an action mode is about to be exited and
// destroyed
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case DEFINITION:
int min = 0;
int max = mTextView.getText().length();
if (mTextView.isFocused()) {
final int selStart = mTextView.getSelectionStart();
final int selEnd = mTextView.getSelectionEnd();
min = Math.max(0, Math.min(selStart, selEnd));
max = Math.max(0, Math.max(selStart, selEnd));
}
// Perform your definition lookup with the selected text
final CharSequence selectedText = mTextView.getText().subSequence(min, max);
// Finish and close the ActionMode
mode.finish();
return true;
default:
break;
}
return false;
}
});
结果
此属性仅用于允许复制或不复制TextView中的文本。我发现,对于我的特定用例,在上的答案比下面的答案要好。我找到了getSelectionStart等,但正在寻找自定义操作模式,这正是我所要找的!这是一个很好的解决方案有一种方法可以突出显示所选文本。在onPrepareActionMode()
中调用menu.clear()
怎么样?它可能更快更安全。