如何在以下代码中多次实现spannable?

时间:2016-05-10 05:45:58

标签: android recursion settext spannable

##由于spannable无法访问onclick侦听器外部的数据,因此整个代码都写在click侦听器内部##

rd.setOnClickListener(new View.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));//

&LT;&GT;

            if (clicked>0){    }   }

1 个答案:

答案 0 :(得分: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);