-4

I want to highlight selected text in android textview.Can anyone tell me the possibility to get the start and end index of the selected text in android textview.

I use the following TextView for selecting a text.

<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"
     />

To highlight specifix string I use following code.How can I get start and end index of selected text.

    SpannableString str = new SpannableString("Highlighted. Not highlighted.");
    str.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 11, 0);
    textView.setText(str);
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
BABU K
  • 917
  • 13
  • 35
  • how would someone select text from a textview. please explain elaborately. – sam Feb 21 '18 at 13:37
  • https://stackoverflow.com/questions/6025818/select-copy-text-in-a-textview/6179365 – MSD Feb 21 '18 at 13:39
  • I don't know people putting down vote without understanding or answering my question.They must add comment without putting down vote. – BABU K Feb 21 '18 at 13:44
  • @DanieleD. My question is different from the suggested answer by you. – BABU K Feb 21 '18 at 13:52

1 Answers1

0

May be this is what you are looking for

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

sample code:

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();
      }
  });
vikas kumar
  • 10,447
  • 2
  • 46
  • 52
  • Please let me try your answer.I don't know this answer will return selected text's start and end index of large text.Thanks for your answer. – BABU K Feb 21 '18 at 13:45
  • Thank you for your answer.This is what I was looking. – BABU K Feb 21 '18 at 13:55