【问题标题】:How to get start and end index of selected text in TextView? [duplicate]如何在 TextView 中获取所选文本的开始和结束索引? [复制]
【发布时间】:2018-08-01 02:42:53
【问题描述】:

我想在 android textview 中突出显示选定的文本。谁能告诉我在 android textview 中获取选定文本的开始和结束索引的可能性。

我使用以下 TextView 来选择文本。

<TextView
    android:id="@+id/textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:textIsSelectable="true"
    android:bufferType="spannable"
     />

为了突出显示特定字符​​串,我使用以下代码。如何获取所选文本的开始和结束索引。

    SpannableString str = new SpannableString("Highlighted. Not highlighted.");
    str.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 11, 0);
    textView.setText(str);

【问题讨论】:

  • 某人如何从文本视图中选择文本。请详细解释。
  • 我不知道有人在不理解或回答我的问题的情况下投反对票。他们必须在不投反对票的情况下添加评论。
  • @DanieleD。我的问题与您建议的答案不同。

标签: android textview highlight


【解决方案1】:

这就是你要找的东西

    int start = textView.getSelectionStart();
    int end = textView.getSelectionEnd();

示例代码:

textView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        ClipboardManager cm = (ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setText(textView.getText());
        int start = textView.getSelectionStart();
        int end = textView.getSelectionEnd();
        Toast.makeText(context, "Copied to clipboard", Toast.LENGTH_SHORT).show();
      }
  });

【讨论】:

  • 请让我试试你的答案。我不知道这个答案会返回所选文本的大文本的开始和结束索引。谢谢你的回答。
  • 感谢您的回答。这就是我正在寻找的。​​span>
猜你喜欢
  • 2019-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多