##由于spannable无法从onclick监听器外部访问数据,因此整个代码都写在onclick listener##内部
rd.setOnClickListener(新视图.OnClickListener(){
@Override
public void onClick(View view) {
int clicked=0;
clicked++; //< click counter>
String extract=tv2.getText().toString();
int startIndex=tv2.getSelectionStart();
int endIndex=tv2.getSelectionEnd();
extract=extract.substring(startIndex,endIndex);
ClipboardManager clipboardManager= (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
clipboardManager.setText(extract); // <Textview selection and clipboard >
int length = extract.length();
Spannable spannable=new SpannableString(extract);
spannable.setSpan(new BackgroundColorSpan(Color.GREEN), 0, length, 0);
// spannable to set the background color
String nsb98=tv2.getText().toString();
int length2=nsb98.length();
String nsb97=nsb98.substring(0,startIndex);
String nsb96=nsb98.substring(endIndex,length2);
tv2.setText(TextUtils.concat(nsb97, spannable,nsb96));//
<>
if (clicked>0){ } }
在onClick()
中使用下面的代码,它应该会给出所需的结果。
Editable text = tv2.getText();
Spannable raw = new SpannableString(text);
BackgroundColorSpan[] spans = raw.getSpans(0, raw.length(), BackgroundColorSpan.class);
final SpannableStringBuilder sb = new SpannableStringBuilder(text.toString());
for (BackgroundColorSpan span : spans) {
sb.setSpan(span, text.getSpanStart(span), text.getSpanEnd(span), text.getSpanFlags(span));
}
sb.setSpan(new BackgroundColorSpan(Color.GREEN), tv2.getSelectionStart(), tv2.getSelectionEnd(), 0);
tv2.setText(sb);