BackgroundColorSpan隐藏文本选择颜色android

时间:2016-06-27 16:35:13

标签: java android

我使用BackgroundColorSpan使用以下代码行

突出显示一些文本TextView
SpannableString text = new SpannableString(textView.getText());
 text.setSpan(new BackgroundColorSpan(Color.YELLOW),start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
 textView.setText(text, TextView.BufferType.SPANNABLE);

但是当我选择那些文本时,BackgroundColorSpan会隐藏文本选择颜色,如屏幕截图所示。我想在BackgroundColorSpan上显示文本选择颜色。任何解决方案?

enter image description here

1 个答案:

答案 0 :(得分:0)

因为 SpannableString TextView 呈现,文字选择由上下文 ActionMode 控制,所以我认为没有一种直接的方式让他们一起工作。但是有一种解决方法。

解决方案的第一部分是实现 CustomSelectionModeCallback 以获取当前选择的文本部分。

textView.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        return true;
    }
    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        //
        // This function is called whenever the selected text is 
        // changed, so you can use this to keep track of which part
        // the text is currently selected
        //
        int start = textView.getSelectionStart();
        int end = textView.getSelectionEnd();
        String slectedText =textView.getText().toString().substring(start, end));
        return true;
    }
    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        return false;
    }
    @Override
    public void onDestroyActionMode(ActionMode mode) {
    }
});

解决方案的第二部分是计算所选文本与当前由 SpannableString 突出显示的文本之间的交集,而不是突出显示相交的部分。由于您可能需要在运行时更改此设置,因此您可能需要使用 SpannableStringBuilder